gpt4 book ai didi

python - 在多个条件下使用 numpy.where 搜索二维数组

转载 作者:行者123 更新时间:2023-12-05 02:16:29 28 4
gpt4 key购买 nike

我有一个二维数组,定义如下:

traces = [['x1',11026,0,0,0,0],
['x0',11087,0,0,0,1],
['x0',11088,0,0,1,3],
['x0',11088,0,0,0,3],
['x0',11088,0,1,0,1]]

我想找到与所选列的多个条件匹配的行的索引。例如我想在这个数组中找到行

row[0]=='x0' & row[1]==11088 & row[3]==1 & row[5]=1

搜索此条件应返回 4。

我尝试使用 numpy.where 但似乎无法使其在多种条件下工作

print np.where((traces[:,0] == 'x0') & (traces[:,1] == 11088) & (traces[:,3] == 1) & (traces[:,5] == 1))

上面创建了警告

FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison   print np.where((traces[:,0] == 'x0') & (traces[:,1] == 11088) & (traces[:,3]
== 1) & (traces[:,5] == 1)) (array([], dtype=int32),)

我也尝试过使用 numpy.logical_and 但它似乎也不起作用,产生了类似的警告。

有什么方法可以使用 numpy.where 而不遍历整个 2D 数组?

谢谢

最佳答案

我强烈假设你做了这样的事情(转换为 np.array):

traces = [['x1',11026,0,0,0,0],
['x0',11087,0,0,0,1],
['x0',11088,0,0,1,3],
['x0',11088,0,0,0,3],
['x0',11088,0,1,0,1]]

traces = np.array(traces)

这显示了所描述的错误。原因可以通过打印结果数组看出:

print(traces)
# array([['x1', '11026', '0', '0', '0', '0'],
# ['x0', '11087', '0', '0', '0', '1'],
# ['x0', '11088', '0', '0', '1', '3'],
# ['x0', '11088', '0', '0', '0', '3'],
# ['x0', '11088', '0', '1', '0', '1']],
# dtype='<U5')

数字已转换为字符串!

在构造包含不同类型值的数组时,numpy 通常会创建一个dtype=object 的数组。这在大多数情况下都有效,但性能不佳。

然而,在这种情况下,numpy 显然试图变得聪明,并将数据转换为字符串类型,它比对象更具体,但足够通用,可以将数字作为字符串。

作为解决方案,将数组显式构造为“对象数组”:

traces = np.array(traces, dtype='object')

print(np.where((traces[:,0] == 'x0') & (traces[:,1] == 11088) & (traces[:,3] == 1) & (traces[:,5] == 1)))
# (array([4], dtype=int32),)

请注意,虽然这可行,但对象数组通常不是一个好主意。请考虑将第一列中的字符串替换为数值。

关于python - 在多个条件下使用 numpy.where 搜索二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49902212/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com