pandas 熊猫数据框中列表中的元素计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48707117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count of elements in lists within pandas data frame
提问by Gaurav Taneja
I need to get the frequency of each element in a list when the list is in a pandas data frame columns
当列表位于Pandas数据框列中时,我需要获取列表中每个元素的频率
In data:
在数据中:
din=pd.DataFrame({'x':[['a','b','c'],['a','e','d', 'c']]})`
x
0 [a, b, c]
1 [a, e, d, c]
Desired Output:
期望输出:
f x
0 2 a
1 1 b
2 2 c
3 1 d
4 1 e
I can expand the list into rows and then perform a group by but this data could be large ( million plus records ) and was wondering if there is a more efficient/direct way.
我可以将列表扩展为行,然后执行分组,但此数据可能很大(数百万条记录),并且想知道是否有更有效/直接的方法。
Thanks
谢谢
回答by jezrael
First flattenvalues of list
s and then count by value_counts
or size
or Counter
:
首先展平list
s 的值,然后按value_counts
orsize
或 or计数Counter
:
a = pd.Series([item for sublist in din.x for item in sublist])
Or:
或者:
a = pd.Series(np.concatenate(din.x))
df = a.value_counts().sort_index().rename_axis('x').reset_index(name='f')
Or:
或者:
df = a.groupby(a).size().rename_axis('x').reset_index(name='f')
from collections import Counter
from itertools import chain
df = pd.Series(Counter(chain(*din.x))).sort_index().rename_axis('x').reset_index(name='f')
print (df)
x f
0 a 2
1 b 1
2 c 2
3 d 1
4 e 1
回答by tmsss
You can also have an one liner like this:
你也可以有这样的单衬:
df = pd.Series(sum([item for item in din.x], [])).value_counts()