Dave
Dave

Reputation: 35

Clarification on indexing numpy array in python

I am a high school student and looking through some numpy code, I found something along the lines of

a = x[:,0:4]

and x was a 2-d array. I know that a[:], refers to all objects in array a, so for x[:,0:4], would it refer to all rows of x and columns with index 0,1,2,3 excluding column with index 4?

Just trying to get confirmation about how this works because I have seen it in several types of code and just wanted to be sure.

Upvotes: 1

Views: 49

Answers (2)

ilyas patanam
ilyas patanam

Reputation: 5324

Yes this is referred to as slice notation and numpy arrays can also use Python's slice notation, so

>>>x = np.arange(25).reshape(5, 5)
>>>a = x[:, 0:4]
>>>a
array([[ 0,  1,  2,  3],
   [ 5,  6,  7,  8],
   [10, 11, 12, 13],
   [15, 16, 17, 18],
   [20, 21, 22, 23]])

If you use the slice notation, x will be a view of a and not a copy, so if you change a value in array x, the value will also be changed in a.

>>>x[1,1] = 1000
>>>a
array([[   0,    1,    2,    3],
       [   5, 1000,    7,    8],
       [  10,   11,   12,   13],
       [  15,   16,   17,   18],
       [  20,   21,   22,   23]])

Upvotes: 0

Mike Müller
Mike Müller

Reputation: 85432

You are right. This a = x[:,0:4] selects the first four columns.

Example:

>>> a = np.arange(25).reshape(5, 5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

You can skip the 0 because a[:,:4] means the same as a[:,0:4]:

>>> a[:,:4]
array([[ 0,  1,  2,  3],
       [ 5,  6,  7,  8],
       [10, 11, 12, 13],
       [15, 16, 17, 18],
       [20, 21, 22, 23]])

You can always think: "First dimension first, second dimension second, and so on." In the 2D case the first dimension is the rows and the second dimension is the columns.

Upvotes: 1

Related Questions