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

3

我是一名有用的助手,可以为您翻译文本。

我有一个panda系列 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
3个回答

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

或者使用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

1

尝试

pd.value_counts([i for i in chain.from_iterable(l.values.tolist())])

1

这里是另一种解决方案,使用 np.hstack()pd.value_counts() 方法:

In [24]: pd.value_counts(np.hstack(l.values))
Out[24]:
2     2
1     2
10    1
4     1
3     1
dtype: int64

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接