Magical index

Magical index

To select a subset that meet certain sequence, simply by passing a specified list or array contains the desired sequence is accomplished:

import numpy as np
arr = np.empty((8,4))

for i in range(8):
    arr[i] = i
print(arr)
print(arr[[4,3,0,6]])

Print Results:

[[0. 0. 0. 0.]
 [1. 1. 1. 1.]
 [2. 2. 2. 2.]
 [3. 3. 3. 3.]
 [4. 4. 4. 4.]
 [5. 5. 5. 5.]
 [6. 6. 6. 6.]
 [7. 7. 7. 7.]]

[[4. 4. 4. 4.]
 [3. 3. 3. 3.]
 [0. 0. 0. 0.]
 [6. 6. 6. 6.]]

You can also be negative by the index. Do not write on a chestnut.

When transmitting a plurality of array index, the situation is somewhat different, this will be selected according to a one-dimensional array element corresponding to each index tuple

arr1 = np.arange(32).reshape((8,4))#重塑数组
print(arr1)
print('---------------|')
arr2 = arr1[[1,5,7,2], [0,3,1,2]]
print(arr2)

Print Results:

[[ 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 25 26 27]
 [28 29 30 31]]
---------------|
[ 4 23 29 10]

In the above chestnuts, the elements (1,0), (5,3), (7,1), (2,2) is selected, if you do not consider the dimension, the index of the array of magical result is always one-dimensional .

Among imagine his results should not be this way, but by a subset of the rectangular area in the ranks of the matrix formed, but can also be achieved in the following way:

print(arr1[[1,5,7,2]])
print('---------------|')
print(arr1[[1,5,7,2]][:,[0,3,1,2]])

Print Results:

[[ 4  5  6  7]
 [20 21 22 23]
 [28 29 30 31]
 [ 8  9 10 11]]
---------------|
[[ 4  7  5  6]
 [20 23 21 22]
 [28 31 29 30]
 [ 8 11  9 10]]

This is the imagination of the way.

Keep in mind that different slice index magical, magical index always assign data to a new array, which means you change the new array produced no effect on the original array, and will slice his views are It is the original array

Guess you like

Origin www.cnblogs.com/chanyuli/p/11762410.html