简体   繁体   中英

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!!

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM