python - 如何计算numpy中多个项目的出现次数?

标签 python numpy

假设有以下 numpy 数组:

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

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

[4, 5]

对应于[1, 2]输入。

numpy 支持吗?

最佳答案

# 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 a set
search = {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]

关于python - 如何计算numpy中多个项目的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078267/

相关文章:

python - 如何从类访问 Python 模块的私有(private)变量

python - Tensorflow 与 Numpy 数学函数

python - psycopg2._psycopg.Diagnostics 的打印结果

python - 可以在 View 或切片上使用 Pandas 替换方法来修改原始数据帧吗?

python - 为什么我收到 ValueError : too many values to unpack (expected 3)?

python - 对字典中的值执行标准偏差

python - 使用 NumPy 快速进行 token 到索引的转换

python - 使用 python 和 tensorflow 从图像中识别数字

python - 将相关系数函数从 NumPy 转换为 Dask

python - 如何在图像阵列中添加 channel ?