gpt4 book ai didi

python - 计算 numpy 数组中的出现次数

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:45 26 4
gpt4 key购买 nike

我有以下两个标签和标签类别维度相同的数组。我想根据类别对标签进行分组并计算标签的出现次数。

如您所见,标签可以共享相同的类别('world'、'hello')。

我知道这可以通过循环轻松完成,但我确信 numpy 有一些巧妙的方法可以更有效地完成它。任何帮助将不胜感激。

# Tag category
A = [10, 10, 20, 10, 10, 10, 20, 10, 20, 20]
# Tags
B = ['hello', 'world', 'how', 'are', 'you', 'world', 'you', 'how', 'hello', 'hello']

预期结果:

[(10, (('hello', 1), ('are', 1), ('you', 1), ('world', 2))), (20, (('how', 1), ('you', 1), ('hello', 2)))]

最佳答案

您可以使用嵌套 collections.defaultdict为此。

在这里,我们将使用 A 中的整数作为外部字典的键,对于每个内部字典,我们将使用 B 中的单词作为键,它们的值将是它们的计数.

>>> from collections import defaultdict
>>> from pprint import pprint
>>> d = defaultdict(lambda: defaultdict(int))
>>> for k, v in zip(A, B):
d[k][v] += 1

现在 d 包含(我将它转换为普通字典,因为它的输出不那么困惑):

>>> pprint({k: dict(v) for k, v in d.items()})
{10: {'are': 1, 'hello': 1, 'how': 1, 'world': 2, 'you': 1},
20: {'hello': 2, 'how': 1, 'you': 1}}

现在我们需要遍历外部字典并在外部列表上调用 tuple(.iteritems()) 以获得所需的输出:

>>> pprint([(k, tuple(v.iteritems())) for k, v in d.items()])
[(10, (('world', 2), ('you', 1), ('hello', 1), ('how', 1), ('are', 1))),
(20, (('how', 1), ('you', 1), ('hello', 2)))]

关于python - 计算 numpy 数组中的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26803491/

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