获取一列列表的频率表 [英] Get a frequency table for a column of lists

查看:57
本文介绍了获取一列列表的频率表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 DataFrame,其中有一列列表.

Suppose I have the DataFrame where I have a column of lists.

df = pd.DataFrame({'A': [['a', 'b', 'c'], ['b'], ['c'], ['a', 'b']]})

输出

Index  A
0      ['a', 'b', 'c']
1      ['b']
2      ['c']
3      ['a', 'b']

如何获得一个频率表,以了解列表在列中出现的频率?

How do I get a frequency table for how often a list appears in the column?

理想的输出看起来像

A               Count
['a', 'b', 'c'] 1
['b']           1
['c']           1
['a', 'b']      1

尝试这样的事情...

df.A.value_counts()

导致错误

TypeError: unhashable type: 'list'

推荐答案

map 到元组,列表不可散列,因为错误提示:

map to tuples, lists are not hashable as the error suggests:

df.A.map(tuple).value_counts().rename_axis('A').reset_index(name='Count')

           A  Count
0  (a, b, c)      1
1     (a, b)      1
2       (b,)      1
3       (c,)      1

这篇关于获取一列列表的频率表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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