What does [i,:] mean in Python?
Asked Answered
D

3

6

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.

Dichlorodifluoromethane answered 31/1, 2019 at 21:52 Comment(1)
numpy slicing notation. I haven't found a good duplicate. If anyone finds one, I have added the "python" tag so you can dupehammer...Englut
U
11

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])

Ulberto answered 31/1, 2019 at 21:58 Comment(3)
Okay thanks, the does help, I do have a for loop that says: for i, degree in enumerate([1,3,6,9]). So I understand what the 2D slicing is for.Dichlorodifluoromethane
Though i also realized I can get the same answers without the comma (ans[i:]).Dichlorodifluoromethane
a[0,:] is different from a[0:]. The second one copies the vector in all rows.Englut
N
4

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.

Navada answered 31/1, 2019 at 21:58 Comment(0)
A
2

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]
Apart answered 31/1, 2019 at 23:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.