索引与切片
索引与切片.png总结一下Numpy
中索引与切片的常用操作,思维导图可以帮助自己快速梳理回顾知识点。个人觉得Numpy
作为一个工具,没必要花太多精力去熟悉每个API
,遇到没见过的API
查看官方文档学习即可。
一维数组
a = np.arange(10)
a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
索引
a[0] = 1
print(a, a[1])
[1 1 2 3 4 5 6 7 8 9] 1
切片
a[0:2] = 2
a
array([2, 2, 2, 3, 4, 5, 6, 7, 8, 9])
# 拷贝数组
b = a[:].copy()
b[0] = 1
print(a == b)
[False True True True True True True True True True]
多维数组
a = np.arange(12).reshape(3,-1)
a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
索引
# ndim从原来的2-->1
print(a[0])
print(a[0, 0]) # 等价于a[0][0]
print('-------')
print(a.ndim)
print(a[0].ndim)
print(a[0, 0].ndim)
[0 1 2 3]
0
-------
2
1
0
dot 索引
b = np.random.randint(1, 100, [2, 2, 3])
print(b)
print(b[1, ...])
print(b[..., 2])
[[[35 86 56]
[18 9 50]]
[[29 94 2]
[48 26 26]]]
[[29 94 2]
[48 26 26]]
[[56 50]
[ 2 26]]
切片
# 切片不改变数组的维度
print(a[:2, 1:])
[[1 2 3]
[5 6 7]]
# 索引 & 切片
# 得到降低一个维度的切片
print(a[1,:2])
[4 5]
布尔索引
data = np.random.randn(7, 4)
names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
data
array([[-0.7508834 , -0.54532566, -0.76911561, -1.62799584],
[ 1.83550152, -0.90720255, 0.5720965 , 0.23752405],
[ 1.02863757, -0.03463182, -0.26193802, 1.60239582],
[ 0.42237715, -1.4393293 , 1.57730021, -0.90482475],
[-0.09214181, 0.17379535, 0.40528223, -2.7919602 ],
[-0.33572487, -0.74226905, 1.16949952, 0.25240986],
[-1.58267947, -0.53052068, 0.20950701, -1.9841287 ]])
names
array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'], dtype='<U4')
names == 'Bob'
array([ True, False, False, True, False, False, False])
data[names=='Bob']
array([[-0.7508834 , -0.54532566, -0.76911561, -1.62799584],
[ 0.42237715, -1.4393293 , 1.57730021, -0.90482475]])
data[names=='Bob', 2:]
array([[-0.76911561, -1.62799584],
[ 1.57730021, -0.90482475]])
神奇索引
a = np.arange(12).reshape(4, -1)
a
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
a[[3, 2, 0, 1]]
array([[ 9, 10, 11],
[ 6, 7, 8],
[ 0, 1, 2],
[ 3, 4, 5]])
a[[3, 2, 1], [2, 0, 1]]
array([11, 6, 4])
a[0, [1, 2]]
array([1, 2])
a[:2, [0, 2]]
array([[0, 2],
[3, 5]])
a[:2, [True, False, True]]
array([[0, 2],
[3, 5]])
网友评论