python - 使用 np.where 查找二维数组中元素的索引给出 ValueError

标签 python numpy

我正在尝试使用 np.where 查找数组中元素的索引,特别是行号

我有一个大小为 1000 x 6 的数组,名为“table”。每行第一个元素是一个 2 x 2 字符串数组,其余均为 0。例如。 “table”中元素的 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),)

关于python - 使用 np.where 查找二维数组中元素的索引给出 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55341458/

相关文章:

python - 使用脚本或工具仅获取 HTML <head> 元素

Python继承: init is having an issue with the number of params

python - 如何使用负值保存 PIL 图像

python - 如何修复 AttributeError : module 'numpy' has no attribute 'square'

python - Python中两个数组所有可能总和的数据框

python - 在 python 中合并两个具有唯一列的 CSV

python - 改变 networkx/matplotlib 力图中的边长和簇间距

python - Gensim 库 Python 3.4 : http://www. lfd.uci.edu/~gohlke/pythonlibs/的安装问题

Python csv writer 截断数字格式

python - 如何在Python PuLP的目标函数中使用外部数据?