gpt4 book ai didi

python - 二维数组的 np.where() 行为

转载 作者:行者123 更新时间:2023-12-01 07:41:22 27 4
gpt4 key购买 nike

我有一个 numpy 二维数组,每个数组元素都包含一个字典。

[[{'foo': 1} {'bar': 2, 'xyz': 7} {} {}]
[{} {'xyz': 7} {'bar': 2} {'foo': 1}]
[{} {'xyz': 7} {'foo': 1} {'bar': 2}]]

我试图返回字典包含给定键的每一行的所有索引。

我当前的解决方案如下所示:

indices = []
for row in arr:
for i in range(len(row)):
if 'foo' in row[i].keys():
indices.append(i)

并返回

[0, 3, 2]

但我想知道是否有更好的方法来使用 np.where() 来编写它

我发现这几乎就是我正在寻找的

np.where([[['foo' in ele.keys()] for ele in row] for row in arr])

但它返回 3 个数组(中间的一个是正确的)

(array([0, 1, 2]), array([0, 3, 2]), array([0, 0, 0]))

我不明白第一个和第三个数组,为什么要创建它们?

最佳答案

In [226]: [[['foo' in ele.keys()] for ele in row] for row in arr]                                    
Out[226]:
[[[True], [False], [False], [False]],
[[False], [False], [False], [True]],
[[False], [False], [True], [False]]]

将其设为数组,给出形状 (3,4,1)。 其中 返回一个数组元组,每个维度一个数组。

使用分组 () 而不是 [],给出一个二维数组:

In [227]: [[('foo' in ele.keys()) for ele in row] for row in arr]                                    
Out[227]:
[[True, False, False, False],
[False, False, False, True],
[False, False, True, False]]

frompyfunc 是将函数应用于数组的每个元素的另一种方法。它往往比显式循环快一点(最多 2 倍),并且在处理对象数据类型数组时特别好:

In [228]: np.frompyfunc(lambda d: 'foo' in d.keys(),1,1)(arr)                                        
Out[228]:
array([[True, False, False, False],
[False, False, False, True],
[False, False, True, False]], dtype=object)
In [229]: np.where(_)
Out[229]: (array([0, 1, 2]), array([0, 3, 2]))

关于python - 二维数组的 np.where() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56692137/

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