Reputation: 171
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.
Upvotes: 6
Views: 15474
Reputation: 673
I guess you are also using numpy
to manipulate data (as a 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've used Python or Java to manipulate matrixes before.
Upvotes: 4
Reputation: 140256
It's specific to the 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]
)
Upvotes: 11
Reputation: 1052
I think in this case [] means the indexing operator for a class object which can be used by defining the getitem method
class A:
def __getitem__(self, key):
pass
key can be literally anything. In your case "[1,:]" key is a tuple containing of "1" and a slice(None, None, None). Such a key can be useful if your class represents multi-dimensional data which you want to access via [] operator. A suggested by others answers this could be a numpy array:
Here is a quick example of how such a multi-dimensional indexing could work:
class A:
values = [[1,2,3,4], [4,5,6,7]]
def __getitem__(self, key):
i, j = key
if isinstance(i, int):
i = slice(i, i + 1)
if isinstance(j, int):
j = slice(j, j + 1)
for row in self.values[i]:
print(row[j])
>>>a = A()
>>>a[:,2:4]
[3, 4]
[6, 7]
>>>a[1,1]
[5]
>>>a[:, 2]
[3]
[6]
Upvotes: 2