我正在尝试使用np.where查找数组中元素的索引,特别是行号
我有一个大小为1000 x 6的数组,称为“表”。每行的第一个元素是2 x 2的字符串数组,其余元素为0。例如。“表格”中元素的5 x 6示例:
[['s',' '] 0 0 0 0 0
[' ',' ']]
[[' ',' '] 0 0 0 0 0
[' ','a']]
[[' ',' '] 0 0 0 0 0
[' ',' ']]
[['p',' '] 0 0 0 0 0
[' ',' ']]
[[' ',' '] 0 0 0 0 0
['b',' ']]
2x2数组都是不同的,我想获取大表中包含特定2x2的数组的索引,特别是行号。
例如。说我有
grid = [['s',' ']
[' ',' ']]
我希望我的代码返回[0] [0]
我已经试过了:
i,j = np.where(table == grid)
并且
i,j = np.where(np.all(table == grid))
我得到以下错误:
ValueError: not enough values to unpack (expected 2, got 1)
使用单个值,例如
index = np.where(table == grid)
不会导致错误,但是print(index)将输出一个空数组:
(array([], dtype=int64),)
从关于Stack Overflow的类似问题中,我似乎无法弄清楚此错误如何适用于我,而我一直盯着它看了很长时间
任何帮助将非常感激
设定:
b = np.array([['s','t'],['q','r']])
c = np.array([['s',' '],[' ',' ']])
a = np.array([[c,0,0,0,0,0],
[c,0,0,0,0,0],
[c,0,0,0,0,0],
[c,0,0,0,0,0],
[b,0,0,0,0,0],
[c,0,0,0,0,0],
[c,0,0,0,0,0],
[c,0,0,0,0,0],
[c,0,0,0,0,0]])
假设您只对第零列感兴趣;编写一个函数来测试一维数组中的每个项目。并将其应用于零列
def f(args):
return [np.all(thing==b) for thing in args]
>>> np.apply_along_axis(f,0,a[:,0])
array([False, False, False, False, True, False, False, False, False])
>>>
在结果上使用np.where
>>> np.where(np.apply_along_axis(f,0,a[:,0]))
(array([4], dtype=int64),)
或遵循numpy.where
文档中的注释:
>>> np.asarray(np.apply_along_axis(f,0,a[:,0])).nonzero()
(array([4], dtype=int64),)
正如@hpaulj指出的那样,这np.apply_along_axis
是没有必要的。所以
>>> [np.all(thing == b) for thing in a[:,0]]
[False, False, False, False, True, False, False, False, False]
>>> np.asarray([np.all(thing == b) for thing in a[:,0]]).nonzero()
(array([4], dtype=int64),)
而且没有Python迭代:
>>> (np.stack(a[:,0])==b).all(axis=(1,2))
array([False, False, False, False, True, False, False, False, False])
>>> (np.stack(a[:,0])==b).all(axis=(1,2)).nonzero()
(array([4], dtype=int64),)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句