计算熊猫系列中值的出现次数?

st1*_*297 3 python 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()
Run Code Online (Sandbox Code Playgroud)

给我:

TypeError: unhashable type: 'list' 
Run Code Online (Sandbox Code Playgroud)

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

chain = itertools.chain(*l)
print(list(chain))
Run Code Online (Sandbox Code Playgroud)

但它给了我:

TypeError: 'list' object is not callable
Run Code Online (Sandbox Code Playgroud)

Psi*_*dom 5

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

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

#2.0     2
#1.0     2
#10.0    1
#4.0     1
#3.0     1
#dtype: int64
Run Code Online (Sandbox Code Playgroud)

或另一种选择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
Run Code Online (Sandbox Code Playgroud)

也可以使用Counterfrom collections

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
Run Code Online (Sandbox Code Playgroud)