1.切片
import numpy as np
#切片和索引
a=np.arange(10)
print(a)
s=slice(2,7,2)
print(a[s])
c=a[2:7:2]
print(c)
#[0 1 2 3 4 5 6 7 8 9]
#[2 4 6]
#[2 4 6]
d=np.arange(9).reshape([3,3])
print(d)
#选取d的第二行及之后的数据
print(d[1:])
#选取d的第三列数据,"..."在行位置上时表示整行
print(d[...,2])#print(d[:,2])
print(d[0,...])#print(d[0,:])
#[[0 1 2]
# [3 4 5]
# [6 7 8]]
#[[3 4 5]
# [6 7 8]]
#[2 5 8]
#[0 1 2]
2.高级索引
import numpy as np
#Numpy高级索引
a=np.arange(15).reshape([3,5])
print(a)
#返回坐标为(0,2),(1,3),(1,4)
print(a[[0,1,1],[2,3,4]])
#借助切片
b=a[1:3,1:3]
print(b)
c=a[1:3,[0,1]]
print(c)
d=a[...,1:]
print(d)
#[[ 0 1 2 3 4]
# [ 5 6 7 8 9]
# [10 11 12 13 14]]
#[2 8 9]
#[[ 6 7]
# [11 12]]
#[[ 5 6]
# [10 11]]
#[[ 1 2 3 4]
# [ 6 7 8 9]
# [11 12 13 14]]
3.bool运算
import numpy as np
a=np.arange(15).reshape([3,5])
print(a)
#bool运算
print(a>5)
print(a[a>5])
# ~(取补运算符)来过滤 NaN
a=np.array([np.nan,1,2,np.nan,3,4,5])
print(np.isnan(a))
print(a[~np.isnan(a)])
#过滤掉非复数元素
a = np.array([1, 2+6j, 5, 3.5+5j])
print (a[np.iscomplex(a)])
#[[ 0 1 2 3 4]
# [ 5 6 7 8 9]
# [10 11 12 13 14]]
#[[False False False False False]
# [False True True True True]
# [ True True True True True]]
#[ 6 7 8 9 10 11 12 13 14]
#[ True False False True False False False]
#[1. 2. 3. 4. 5.]
#[2. +6.j 3.5+5.j]
4.花式索引
import numpy as np
#花式索引
x=np.arange(32).reshape((8,4))
print(x)
#[[ 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]]
#传入顺序索引数组
print (x[[4,2,1,7]])
#[[16 17 18 19]
# [ 8 9 10 11]
# [ 4 5 6 7]
# [28 29 30 31]]
#传入倒序索引数组
print (x[[-4,-2,-1,-7]])
#[[16 17 18 19]
# [24 25 26 27]
# [28 29 30 31]
# [ 4 5 6 7]]
#按照行选取,再按顺序将列排序,获得一个矩形
print(x[[1,5,7,2]][:,[0,3,1,2]])
#先按先选取第1、5、2、7行,每一行再按第0个、第3个、第1个、第2个排序
# [[ 4 7 5 6]
# [20 23 21 22]
# [28 31 29 30]
# [ 8 11 9 10]]
#np.ix_函数,能把两个一维数组 转换为 一个用于选取方形区域的索引器,
#直接往np.ix_()里扔进两个一维数组[1,5,7,2],[0,3,1,2],就能先按我们要求选取行,
#再按顺序将列排序,跟上面得到的结果一样,而不用写“[ : , [0,3,1,2] ]”
print (x[np.ix_([1,5,7,2],[0,3,1,2])])
#[[ 4 7 5 6]
# [20 23 21 22]
# [28 31 29 30]
# [ 8 11 9 10]]
参考:https://www.runoob.com/numpy/numpy-advanced-indexing.html
以上,记录本人学习过程。