简体   繁体   English

如何计算 pandas 系列列表中每个元素的出现次数?

[英]How to count occurrence of each element in pandas series of lists?

I'm a newbie and quite stuck with my python project.我是一个新手,非常坚持我的 python 项目。 I have a pandas series containing lists, like this:我有一个包含列表的 pandas 系列,如下所示:

>> df.head()
>> column1       
   ['A', 'B']
   ['A']
   ['A', 'C']
   ['A', 'B', 'C']
   ['B']

The desired output should be like this:所需的 output 应该是这样的:

>> column1   column2
    'A'         4
    'B'         3
    'C'         2

It doesn't matter whether column1 is a string or a list with one element. column1是字符串还是具有一个元素的列表都没有关系。

I tried these:我试过这些:

df.groupby('column1').count()

df['column1'].value_counts()

But both gave me:但两者都给了我:

TypeError: unhashable type: 'list'

Also tried:也试过:

df.groupby('column1')

But it does not display results.但它不显示结果。

Tried solutions here ( How to print a groupby object ) but none worked:(在这里尝试了解决方案( 如何通过 object 打印一个组)但没有一个有效:(

Try:尝试:

df1['column1'].explode().groupby().count()

or或者

df1.explode('column1').groupby('column1').count()
df.explode('Column1').groupby('Column1').size().reset_index(name='Column2')

Output: Output:

  Column1  Column2
0       A        4
1       B        3
2       C        2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何计算熊猫中每个唯一值的出现次数 - how to count occurrence of each unique value in pandas 如何有效地将系列索引添加到Pandas系列列表数组的每个列表元素中? - How can I add the series index to each list element a Pandas series of arrays of lists efficiently? 带有一系列列表的 pandas 的元素明智“输入” - Element wise 'in' for pandas with a Series of Lists 计算列表熊猫数据框列中元素的出现次数 - Count occurrence of element in column of lists panda dataframe pandas:计算列表中每个元素在列表列中唯一出现的次数 - pandas: count the number of unique occurrences of each element of list in a column of lists Pandas 系列字符串列表如何计数和 append 到 df 每行 - Pandas Series of lists of strings how to count and append to df per row 如何计算二维直方图中每个 bin 中每个唯一 ID 的出现次数(python 或 pandas) - How to count occurrence of each unique ID in each bin in a 2D histogram (python or pandas) 有没有一种方法可以根据发生的顺序计数来聚合 pandas 中的时间序列? - Is there a method to aggregate time series in pandas based on the sequential count of an occurrence? 如何计算一列列表中每个唯一值的出现次数 Pandas - How to count occurrences of each unique value within a column of lists Pandas 从 pandas 系列中的每一行中提取某个字符串的最后一次出现 - Extracting last occurrence of a certain string from each row in a pandas series
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM