如何计算 ndarray 中某个项目的出现次数? [英] How to count the occurrence of certain item in an ndarray?

查看:31
本文介绍了如何计算 ndarray 中某个项目的出现次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,我有一个 ndarray y打印为 array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

In Python, I have an ndarray y that is printed as array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

我正在尝试计算这个数组中有多少 0 和多少 1.

I'm trying to count how many 0s and how many 1s are there in this array.

但是当我输入 y.count(0)y.count(1) 时,它说

But when I type y.count(0) or y.count(1), it says

numpy.ndarray 对象没有属性 count

我该怎么办?

推荐答案

a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
unique, counts = numpy.unique(a, return_counts=True)
dict(zip(unique, counts))

# {0: 7, 1: 4, 2: 1, 3: 2, 4: 1}

非 numpy 方式:

使用collections.Counter;

import collections, numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
collections.Counter(a)

# Counter({0: 7, 1: 4, 3: 2, 2: 1, 4: 1})

这篇关于如何计算 ndarray 中某个项目的出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆