np.where()[0]和np.where()[1]的具体使⽤
本⽂主要介绍了np.where()[0] 和 np.where()[1]的具体使⽤,以及np.where()的具体⽤法,废话不多说,具体如下:
import numpy as np
a = np.arange(12).reshape(3,4)
print('a:', a)
print('np.where(a > 5):', np.where(a > 5))
print('a[np.where(a > 5)]:', a[np.where(a > 5)])
print('np.where(a > 5)[0]:', np.where(a > 5)[0])
print('np.where(a > 5)[1]:', np.where(a > 5)[1])
print(a[np.where(a > 5)[0], np.where(a > 5)[1]])
a: [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
np.where(a > 5): (array([1, 1, 2, 2, 2, 2]), array([2, 3, 0, 1, 2, 3]))
a[np.where(a > 5)]: [ 6 7 8 9 10 11]
np.where(a > 5)[0]: [1 1 2 2 2 2]
np.where(a > 5)[1]: [2 3 0 1 2 3]
[ 6 7 8 9 10 11]
np.where()[0] 表⽰⾏索引,np.where()[1]表⽰列索引
numpy.where() 有两种⽤法:
1. np.where(condition, x, y)
满⾜条件(condition),输出x,不满⾜输出y。
如果是⼀维数组,相当于[xv if c else yv for (c,xv,yv) in zip(condition,x,y)]
>>> aa = np.arange(10)
>>> np.where(aa,1,-1)
array([-1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) # 0为False,所以第⼀个输出-1
>>> np.where(aa > 5,1,-1)
array([-1, -1, -1, -1, -1, -1, 1, 1, 1, 1])
>>> np.where([[True,False], [True,True]], # 官⽹上的例⼦
[[1,2], [3,4]],pycharm安装教程和使用
[[9,8], [7,6]])
array([[1, 8],
[3, 4]])
上⾯这个例⼦的条件为[[True,False], [True,False]],分别对应最后输出结果的四个值。第⼀个值从[1,9]中选,因为条件为True,所以是选1。第⼆个值从[2,8]中选,因为条件为False,所以选8,后⾯以此类推。类似的问题可以再看个例⼦:>>> 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) 元素的坐标 (等价于o)。这⾥的坐标以tuple的形式给出,通常原数组有多少维,输出的tuple中就包含⼏个数组,分别对应符合条件元素的各维坐标。
>>> a = np.array([2,4,6,8,10])
>>> np.where(a > 5) # 返回索引
(array([2, 3, 4]),)
>>> a[np.where(a > 5)] # 等价于 a[a>5]
array([ 6, 8, 10])
>>> np.where([[0, 1], [1, 0]])
(array([0, 1]), array([1, 0]))
上⾯这个例⼦条件中[[0,1],[1,0]]的真值为两个1,各⾃的第⼀维坐标为[0,1],第⼆维坐标为[1,0] 。
下⾯看个复杂点的例⼦:
>>> a = np.arange(27).reshape(3,3,3)
>>> a
array([[[ 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]]])
>>> np.where(a > 5)
(array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2]),
array([2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2]),
array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]))
# 符合条件的元素为
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]]
所以np.where会输出每个元素的对应的坐标,因为原数组有三维,所以tuple中有三个数组。
需要注意的⼀点是,输⼊的不能直接是list,需要转为array或者为array才⾏。⽐如range(10)和np.arange(10)后者返回的是数组,使⽤np.where才能达到效果。
到此这篇关于np.where()[0] 和 np.where()[1]的具体使⽤的⽂章就介绍到这了,更多相关np.where()[0] 和 np.where()[1]内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论