一、np.where(condition,x=None,y=None)
1、当condition为True时,将执行x,否则执行y
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,])
b = np.where(a > 6,a * 2,a)
print(b)
2、特殊情况下,当只有condition时,将返回满足condition的数据索引。注意,返回的数据类型为元组(index,type)。
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,])
b = np.where(a > 6)
print(b)
当原数据为多维时,返回也为多维数组的索引。(以二维为例,第一维为行索引,第二维为列索引)
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12]).reshape(3,4)
print(a)
b = np.where(a > 6)
print(b)
二、object.argmax(axis=None)
以参数axis为指引,决定按哪一个方向寻找最大值。当参数不指定时,默认先平铺所有数据,后寻找最大值。
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12]).reshape(3,4)
print(a)
#axis = 0,按列方向寻找最大索引
axis_0 = a.argmax(axis=0)
print('--axis=0---')
print(axis_0)
#axis = 1,按行方向寻找最大索引
axis_1 = a.argmax(axis=1)
print('--axis=1---')
print(axis_1)
#axis=None
axis_none = a.argmax()
print('--axis=1---')
print(axis_none)
三、两者最大区别
当待寻找对象存在相同数据时,前者p.where(condition)可以返回多个索引,而后者object.argmax()只能返回对应相同数据中所有索引的最小值。
import numpy as np
a = np.array([1, 2, 5, 4, 5, 5])
print(a)
b_where = np.where(a == 5)
print(b_where)
print('--------')
b_argmax = a.argmax()
print(b_argmax)