【python】np.where和np.argwhere、np.squeeze

1、用法:np.where(condition, x, y) 和 np.where(condition)

返回:条件满足则返回x,不满足则返回y

只有条件 (condition),没有x和y时,则输出满足条件 (即非0) 元素的坐标 (等价于numpy.nonzero)。这里的坐标以tuple的形式给出,通常原数组有多少维,输出的tuple中就包含几个数组,分别对应符合条件元素的各维坐标。

例:

import numpy as np

a= np.arange(10)
print(a)
a=[0 1 2 3 4 5 6 7 8 9]

b = np.where(aa>5, 1, -1)#大于5输出1,否则输出-1
print(b)
b = [-1 -1 -1 -1 -1 -1  1  1  1  1]

参考:https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

https://www.cnblogs.com/massquantity/p/8908859.html

2、用法:np.argwhere(a)

返回:非0的数组元素的索引,其中a是待索引数组的条件

例:

import numpy as np
x = np.arange(6).reshape(2,3)
print(x)
x=[[0 1 2]
 [3 4 5]]

y = np.argwhere(x>1) #x所有元素中大于1的元素的索引,分别是第0行第2列...以此类推
print(y)
y=[[0 2]
 [1 0]
 [1 1]
 [1 2]]

参考:https://docs.scipy.org/doc/numpy/reference/generated/numpy.argwhere.html

https://blog.csdn.net/u012193416/article/details/79672514

3、用法:np.squeeze(a, axis=None)

返回:从数组shape中删除一维项。

例:

import numpy as np
m = np.arange(6).reshape(1,1,6)
print(m)
m=[[[0 1 2 3 4 5]]]

n = np.squeeze(m)#第一维和第二维都是1,故删除
print(n)
n=[0 1 2 3 4 5]

参考:https://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html

你可能感兴趣的:(Python函数)