【问题标题】:How to count occurances of multiple items in numpy? [duplicate]如何计算numpy中多个项目的出现? [复制]
【发布时间】:2020-03-23 11:39:30
【问题描述】:

假设以下 numpy 数组:

[1,2,3,1,2,3,1,2,3,1,2,2]

我想count([1,2]) 在一次运行中计算所有出现的 1 和 2,产生类似

[4, 5]

对应于[1, 2] 输入。

numpy 支持吗?

【问题讨论】:

标签: python numpy


【解决方案1】:
# Setting your input to an array
array = np.array([1,2,3,1,2,3,1,2,3,1,2,2])

# Find the unique elements and get their counts
unique, counts = np.unique(array, return_counts=True)

# Setting the numbers to get counts for as an array
search = np.array([1, 2])

# Gets the counts for the elements in search
search_counts = [counts[i] for i, x in enumerate(unique) if x in search]

这将输出 [4, 5]

【讨论】:

    猜你喜欢
    • 2021-02-28
    • 2012-07-23
    • 2014-10-16
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 2019-06-16
    相关资源
    最近更新 更多