Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [i,:] mean in Python?

So I'm finished one part of this assignment I have to do. There's only one part of the assignment that doesn't make any sense to me.

I'm doing a LinearRegression model and according to others I need to apply ans[i,:] = y_poly at the very end, but I never got an answer as to why.

Can someone please explain to me what [i,:] means? I haven't found any explanations online.

like image 512
Preston Avatar asked Jan 31 '19 21:01

Preston


People also ask

What does it mean in Python list [: 1?

In Python, [::-1] means reversing a string, list, or any iterable with an ordering. For example: hello = "Hello world"

What does 0 :] mean in Python?

It acts as an indicator in the format method that if you want it to be replaced by the first parameter(index zero) of format. Example : print(42+261={0}.format(303)) Here, {0} will be replaced by 303.

What does [: n mean in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text.

What does [:: 4 mean in Python?

string[::4] reads “default start index, default stop index, step size is four—take every fourth element“. string[2::2] reads “start index of two, default stop index, step size is two—take every second element starting from index 2“.


2 Answers

It's specific to numpy module, used in most data science modules.

ans[i,:] = y_poly

this is assigning a vector to a slice of numpy 2D array (slice assignment). Self-contained example:

>>> import numpy
>>> a = numpy.array([[0,0,0],[1,1,1]])
>>> a[0,:] = [3,4,5]
>>> a
array([[3, 4, 5],
       [1, 1, 1]])

There is also slice assignment in base python, using only one dimension (a[:] = [1,2,3])

like image 163
Jean-François Fabre Avatar answered Sep 29 '22 13:09

Jean-François Fabre


I guess you are also using numpy to manipulate data (as matrix) ?

If based on numpy, ans[i,:] means to pick the ith 'row' of ans with all of its 'columns'. Note,when dealing with numpy arrays, we should (almost) always use [i, j] instead of [i][j]. This might be counter-intuitive if you used Python or Java to manipulate matrix before.

like image 33
Jacqueline P. Avatar answered Sep 29 '22 14:09

Jacqueline P.