我有一个 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/