Kakarot_7
Kakarot_7

Reputation: 342

2-D arrays - Slicing and Indexing

Consider the following code:

arr = np.random.randn(3,3)
print(arr)

>>> array([[-0.46734444,  0.56493252, -0.26263957],
           [-0.08779416, -2.29891065, -0.49095811],
           [-1.75290304,  0.21304592, -0.91466817]])

I tried to get the top right 2 X 2 square matrix using these 2 methods:

print(arr[:2,1:])    
print(arr[:2][1:]) 

>>> [[ 0.56493252 -0.26263957]
     [-2.29891065 -0.49095811]]

>>> [[-0.08779416 -2.29891065 -0.49095811]]

However, the 2nd method gave wrong answer. I do not understand the behaviour of 2nd method. Please explain!!

Upvotes: 0

Views: 33

Answers (1)

Balaji Ambresh
Balaji Ambresh

Reputation: 5012

  1. row index and column index start at 0
  2. when you slice by a list, the start index is inclusive and end index is exclusive. For instance, arr[:2] will give you a list of row[0] and row[1]

print(arr[:2,1:])

  1. You're taking taking row[0] and row[1] and taking all columns starting from the 1st column from the 2 rows.

print(arr[:2][1:])

  1. You're taking row[0] and row[1] via arr[:2]
  2. You're again taking just the 1st row from the previous result.

Hope this helps.

Upvotes: 2

Related Questions