gpt4 book ai didi

python - 如何在 numpy 数组中找到元组的索引?

转载 作者:太空宇宙 更新时间:2023-11-04 11:17:00 29 4
gpt4 key购买 nike

我有一个 numpy 数组:

groups=np.array([('Species1',), ('Species2', 'Species3')], dtype=object)

当我询问 np.where(groups == ('Species2', 'Species3')) 甚至 np.where(groups == groups[1]) 我得到一个空回复:(array([], dtype=int64),)

为什么会这样,我怎样才能得到这样一个元素的索引?

最佳答案

这里的问题可能是 array.__contains__() 的实现方式。参见 here .基本上问题是

print(('Species2', 'Species3') in groups)

打印错误。如果您仍然想使用 numpy.where 函数,而不是像另一个答案所建议的那样使用 for 循环,那么最好以某种方式构造一个合适的真值掩码。例如

x = np.array(list(map(lambda x: x== ('Species2', 'Species3'), groups)))
print(np.where(x))

给出正确的结果。不过,可能还有更优雅的方法。

关于python - 如何在 numpy 数组中找到元组的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56788435/

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