pandas 数据框中列表中元素的数量 [英] Count of elements in lists within pandas data frame

查看:82
本文介绍了 pandas 数据框中列表中元素的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当列表位于pandas数据框列中时,我需要获取列表中每个元素的频率

I need to get the frequency of each element in a list when the list is in a pandas data frame columns

在数据中:

din=pd.DataFrame({'x':[['a','b','c'],['a','e','d', 'c']]})`

              x
0     [a, b, c]
1  [a, e, d, c]

所需的输出:

   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.

谢谢

推荐答案

第一个

First flatten values of lists and then count by value_counts or size or Counter:

a = pd.Series([item for sublist in din.x for item in sublist])

或者:

a = pd.Series(np.concatenate(din.x))


df = a.value_counts().sort_index().rename_axis('x').reset_index(name='f')

或者:

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

这篇关于 pandas 数据框中列表中元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆