python - 计算 Pandas 系列中值的出现次数?

标签 python pandas

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

我需要得到类似的东西:

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

l.value_counts()

给我:

TypeError: unhashable type: 'list' 

我什至试过像这样压平列表:

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

但它给了我:

TypeError: 'list' object is not callable

最佳答案

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

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

关于python - 计算 Pandas 系列中值的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40825317/

相关文章:

python - 使用中间件存储的数据异步更新页面

python - window : Python SSL certificate verify failed

python - Bokeh Python : Select dropdown is updating ColumnDataSource but not updating the graph

python - 如何使用 python 迭代 df 中的字符串

python - 如何将一系列整数转换为日期?

python - 使用 lstm 进行 IMDB 评论的准确性非常低

python - 如何在 Python 中保持列表静态?

python - 从数据框行中的列表(包含标签)中获取唯一值

Python Pandas 滚动聚合一列列表

pandas - pandas 峰度是如何定义的?