索引和切片:
#一维
a1=np.arange(0,20)
print(a1)
print(a1[1])
>>>[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] 1
#多维
a2=np.arange(0,20).reshape(4,5)
print(a2)
print(a2[1]) #获取的是第二行的数据(索引为1的行)
print(a2[0:2]) #获取[0,2)行的数据
print(a2[[0,1,3]]) #获取不连续行的数据 [[ *,*,* ]]
print(a2[[-1,-3]]) #用负数进行索引
print('----'*10)
print(a2[2,2]) #获取某行某列的数
print(a2[1:3,1:3]) #获取[1:3)行的[1:3)列的数据
print(a2[[1,2],[2,3]]) #获取(1,2)和(2,3)的两个数据,这也叫花式索引
print(a2[:,1]) #获取第一列的数据
>>>[[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] >>> [5 6 7 8 9] >>> [[0 1 2 3 4] [5 6 7 8 9]] >>> [[ 0 1 2 3 4] [ 5 6 7 8 9] [15 16 17 18 19]] >>> [[15 16 17 18 19] [ 5 6 7 8 9]] ---------------------------------------- >>> 12 >>> [[ 6 7] [11 12]] >>> [ 7 13] >>> [ 1 6 11 16]
#布尔索引
print(a2<10) #返回一个新的数组,这个数组中的值全部都是bool类型
>>>
[[ True True True True True] [ True True True True True] [False False False False False] [False False False False False]]
#提取a2中<10的数
a3=a2<10
print(a2[a3])
a3 = a2[(a2 < 5) | (a2 > 10)]
print(a3)
>>> [0 1 2 3 4 5 6 7 8 9]
>>> [ 0 1 2 3 4 11 12 13 14 15 16 17 18 19]
#值的替换
a2[3] = 0 #将第三行的所有值都替换成0
print(a2)
a2[a2 < 10] = 0 #将小于10的所有值全部都替换成0
print(a2)
# where函数:
a3 = np.where(a2 < 10,1,0) #把a1中所有小于10的数全部变成1,其余的变成0
print(a3)
>>>
[[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [ 0 0 0 0 0]]>>>
[[ 0 0 0 0 0] [ 0 0 0 0 0] [10 11 12 13 14] [ 0 0 0 0 0]]>>>
[[1 1 1 1 1] [1 1 1 1 1] [0 0 0 0 0] [1 1 1 1 1]]
numpy.where() 有两种用法:
1. np.where(condition, x, y),满足条件(condition),输出x,不满足输出y。
aa = np.arange(10)
print(aa)
print(np.where(aa,1,-1))
#相当于np.where(aa != 0,1,-1)
>>>[0 1 2 3 4 5 6 7 8 9] [-1 1 1 1 1 1 1 1 1 1]
np.where(aa>5,1,0) #aa中大于5的返回1,否则返回0
np.where([[True,False], [True,True]],
[[1,2], [3,4]],
[[9,8], [7,6]])
#第一个值从[1,9]中选,因为条件为True,所以是选第1个。
#第二个值从[2,8]中选,因为条件为False,所以选第二个,后面以此类推。
>>> array([[1, 8], [3, 4]])
#同理
a=10
np.where([[a > 5,a < 5], [a == 10,a == 7]],
[["chosen","not chosen"], ["chosen","not chosen"]],
[["not chosen","chosen"], ["not chosen","chosen"]])
>>> array([['chosen', 'chosen'], ['chosen', 'chosen']], dtype='<U10')
2. np.where(condition)
只有条件 (condition),没有x和y,则输出满足条件 (即非0) 元素的坐标 (等价于numpy.nonzero)。这里的坐标以tuple的形式给出,通常原数组有多少维,输出的tuple中就包含几个数组,分别对应符合条件元素的各维坐标。
a = np.array([2,4,6,8,10])
np.where(a > 5)
a[np.where(a > 5)] # 等价于 a[a>5]
>>> (array([2, 3, 4], dtype=int64),)
>>> array([ 6, 8, 10])