2024-04-24 21:07:17 发布
网友
我有一个熊猫系列l=pd.Series([3, 1, 4, 2, [1, 2, 10]])
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()
给我:
我甚至试着把名单弄平:
chain = itertools.chain(*l) print(list(chain))
但它给了我:
TypeError: 'list' object is not callable
试试看
pd.value_counts([i for i in chain.from_iterable(l.values.tolist())])
这是另一种解决方案,它使用np.hstack()和pd.value_counts()方法:
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
如果数据大小不是很大,可以使用以下解决方法:
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的选项:
chain
也可以从collections使用Counter:
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
试试看
这是另一种解决方案,它使用np.hstack()和
pd.value_counts()
方法:如果数据大小不是很大,可以使用以下解决方法:
或另一个带有
^{pr2}$chain
的选项:也可以从
collections
使用Counter
:相关问题 更多 >
编程相关推荐