计算 pandas 系列中值的出现? [英] Counting occurrence of values in a Panda series?

查看:78
本文介绍了计算 pandas 系列中值的出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫系列l=pd.Series([3, 1, 4, 2, [1, 2, 10]])

我需要得到类似的东西:

I need to get something like:

value  count
3       1
1       2
4       1
2       2
10      1

l.value_counts()

给我:

TypeError: unhashable type: 'list' 

我什至试图将列表变平:

I even tried to flatten the list like this:

chain = itertools.chain(*l)
print(list(chain))

但这给了我

TypeError: 'list' object is not callable

推荐答案

如果您的数据量不是很大,则可以使用以下解决方法:

If your data size is not very large, you can use this work around:

l.apply(pd.Series).stack().value_counts()

#2.0     2
#1.0     2
#10.0    1
#4.0     1
#3.0     1
#dtype: int64

或带有chain的另一个选项:

from itertools import chain
pd.Series(list(chain.from_iterable(i if isinstance(i, list) else [i] for i in l))).value_counts()

#2     2
#1     2
#10    1
#4     1
#3     1
#dtype: int64

并且还可以使用collections中的Counter:

from itertools import chain
from collections import Counter
pd.Series(Counter(chain.from_iterable(i if isinstance(i, list) else [i] for i in l)))

#2     2
#1     2
#10    1
#4     1
#3     1
#dtype: int64

这篇关于计算 pandas 系列中值的出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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