【基本工具】S02E02 ndarray高维数组的索引和分片技巧

# 0.本集概览

1.ndarray高维数组的索引与切片
2.布尔索引与条件赋值
3.指定行和列的选取

# 1.ndarray数组的索引和切片

## 1.1.一维数组的情况

import numpy as np

arr = np.arange(10)
print(arr)
print(arr[5])
print(arr[5:8])  

[0 1 2 3 4 5 6 7 8 9]
5
[5 6 7]

import numpy as np

arr = np.arange(10)
arr[5:8] = 999
print(arr)  

[  0   1   2   3   4 999 999 999   8   9]

import numpy as np

arr = np.arange(10)
temp = arr[5:8]
temp[1] = 888
print(arr)  

[  0   1   2   3   4   5 888   7   8   9]

import numpy as np

arr = np.arange(10)
temp = arr[5:8].copy()
temp[1] = 888
print(arr)  

[0 1 2 3 4 5 6 7 8 9]

## 1.2.高维数组索引

import numpy as np

arr2d = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr2d[2])
print(arr2d[0,1])
print(arr2d[0][1])  

[7 8 9]
2
2

import numpy as np

arr3d = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
print(arr3d[0])
print(arr3d[1][0])
print(arr3d[0][0][1]) 

[[1 2 3]  [4 5 6]]
[7 8 9]
2

## 1.3.视图还是拷贝？

import numpy as np

arr3d = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
arr3d[0] = 111
print(arr3d)  

[[[111 111 111]   [111 111 111]]
[[  7   8   9]   [ 10  11  12]]]

import numpy as np

arr3d = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
arr_cpy = arr3d[0].copy()
arr3d[0] = 111
print(arr3d) 

[[[111 111 111]   [111 111 111]]
[[  7   8   9]   [ 10  11  12]]]  

arr3d[0] = arr_cpy
print(arr3d)  

[[[ 1  2  3]   [ 4  5  6]]
[[ 7  8  9]   [10 11 12]]]

## 1.4.高维数组切片

import numpy as np

arr2d = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr2d[:2,1:])  

[[2 3]  [5 6]]

import numpy as np

arr2d = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr2d[:2,1])  

[2 5]

import numpy as np

arr2d = np.array([[1,2,3],[4,5,6],[7,8,9]])
arr2d[:2,1:] = 0
print(arr2d)  

[[1 0 0]  [4 0 0]  [7 8 9]]

# 2.布尔索引

`
import numpy as np

names = np.array(['tom','bob','bill','jack','tom'])
arr_bool = names == 'tom' print(arr_bool)