gpt4 book ai didi

python - 为元组数组创建 bool 掩码

转载 作者:行者123 更新时间:2023-11-28 18:13:16 25 4
gpt4 key购买 nike

我有一个二维 numpy 数组,其形状为 (3, 3) 且 dtype=object,其元素是形式为 (str, str, float) 的元组。

template = ('Apple', 'Orange', 5.0)
my_array = np.array([None] * 9).reshape((3,3))

for i in range(my_array.shape[0]):
for j in range(my_array.shape[1]):
my_array[i, j] = template

但是当我尝试获取 bool 掩码时

print(my_array == template)

答案都是假的

[[False False False]
[False False False]
[False False False]]

然而元素方面的比较仍然有效

print(my_array[0,0] == template) # This prints True

为什么 bool 掩码返回所有 False,我该如何让它工作?

附言我已经搜索了相关主题,但无法使用任何...

Array of tuples in Python
Restructuring Array of Tuples
Apply function to an array of tuples
Filter numpy array of tuples

最佳答案

这里发生的是在 Python 中 tuples are compared by position.所以当你这样做的时候

my_array == template

你实际上在做什么(按行)是:

('Apple', 'Orange', 5.0) == 'Apple'
('Apple', 'Orange', 5.0) == 'Orange'
('Apple', 'Orange', 5.0) == 5.0

要验证情况是否如此,请尝试使用以下示例进行试验:

>>> other_array = np.array(['Apple', 'Orange', 5.0] * 3).reshape(3,3)
>>> other_array
array([['Apple', 'Orange', '5.0'],
['Apple', 'Orange', '5.0'],
['Apple', 'Orange', '5.0']], dtype='<U6')
>>> other_array == template
array([[ True, True, True],
[ True, True, True],
[ True, True, True]])

我不知道有什么简单的方法可以解决这个问题并使直接相等比较起作用。如果黑客足够并且你的数组不是太大你可以尝试:

mask = np.array(list(map(lambda x: x == template,
my_array.flatten()))).reshape(my_array.shape)

mask = np.array([x == template for x in my_array.flatten()]).reshape(my_array.shape)

为什么需要元组数组?你不能在你的数组中有另一个维度,或者使用 pandas 作为你的分类变量吗?

关于python - 为元组数组创建 bool 掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964981/

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