[Python Cookbook] Numpy Array Slicing and Indexing

1-D Array

Indexing

Use bracket notation [ ] to get the value at a specific index. Remember that indexing starts at 0.

1 import numpy as np
2 a=np.arange(12)
3 a
4 # start from index 0
5 a[0]
6 # the last element
7 a[-1]

Output:

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

0

11

 

Slicing

Use : to indicate a range. 

array[start:stop] 

A second : can be used to indicate step-size. 

array[start:stop:stepsize]

Leaving start or stop empty will default to the beginning/end of the array.

1 a[1:4]
2 a[-4:]
3 a[-5::-2] #starting 5th element from the end, and counting backwards by 2 until the beginning of the array is reached

Output:

array([1, 2, 3, 4])

array([ 8,  9, 10, 11])

array([7, 5, 3, 1])

 

Multidimensional Array

1 r = np.arange(36)
2 r.resize((6, 6))
3 r

Output:

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, 25, 26, 27, 28, 29],

       [30, 31, 32, 33, 34, 35]])

Use bracket notation to index: 

array[row, column] 

and use : to select a range of rows or columns

1 r[2, 2]
2 r[3, 3:6]
3 r[:2, :-1]#selecting all the rows up to (and not including) row 2, and all the columns up to (and not including) the last column
4 r[-1, ::2]#selecting the last row, and only every other element

Output:

14

array([21, 22, 23])

array([[ 0,  1,  2,  3,  4],

       [ 6,  7,  8,  9, 10]])

array([30, 32, 34])

We can also select nonadjacent elements by

r[[2,3],[4,5]] 

Output:

array([16, 23])

Conditional Indexing

r[r > 30]

Output:

array([31, 32, 33, 34, 35])

Note that if you change some elements in the slice of an array, the original array will also be change. You can see the following example:

1 r2 = r[:3,:3]
2 print(r2)
3 print(r)
4 r2[:] = 0
5 print(r2)
6 print(r)

Output:

[[ 0  1  2]

 [ 6  7  8]

 [12 13 14]]

 

[[ 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 32 33 34 35]]

 

[[0 0 0]

 [0 0 0]

 [0 0 0]]

 

[[ 0  0  0  3  4  5]

 [ 0  0  0  9 10 11]

 [ 0  0  0 15 16 17]

 [18 19 20 21 22 23]

 [24 25 26 27 28 29]

 [30 31 32 33 34 35]]

To avoid this, use r.copy to create a copy that will not affect the original array.

1 r_copy = r.copy()
2 print(r_copy, '\n')
3 r_copy[:] = 10
4 print(r_copy, '\n')
5 print(r)

Output:

[[ 0  0  0  3  4  5]

 [ 0  0  0  9 10 11]

 [ 0  0  0 15 16 17]

 [18 19 20 21 22 23]

 [24 25 26 27 28 29]

 [30 31 32 33 34 35]] 

 

[[10 10 10 10 10 10]

 [10 10 10 10 10 10]

 [10 10 10 10 10 10]

 [10 10 10 10 10 10]

 [10 10 10 10 10 10]

 [10 10 10 10 10 10]] 

 

[[ 0  0  0  3  4  5]

 [ 0  0  0  9 10 11]

 [ 0  0  0 15 16 17]

 [18 19 20 21 22 23]

 [24 25 26 27 28 29]

 [30 31 32 33 34 35]]

猜你喜欢

转载自www.cnblogs.com/sherrydatascience/p/10223241.html