python pandas 计算列中列表内的出现次数

标签 python pandas dataframe

假设我有一个像

这样的数据框
    A     B     
0  [1,2]  Q     

1  [1,3]  Q     

2  [4,2]  Q     

我想要 A 列列表中每个元素的计数

所以我想要的结果是

    Number  Count
0     1       2

1     2       2

2     3       1

3     4       1

我不知道该怎么做。提前谢谢你

最佳答案

将列表系列转换为数据框,堆叠列并在该系列上使用 value_counts 即

count = pd.DataFrame(df['A'].values.tolist()).stack().value_counts()

pd.DataFrame({'Count':count.values,'Number':count.index})

  Count  Number
0      2       2
1      2       1
2      1       4
3      1       3

# demo dataframe : df = pd.DataFrame({'A': [[1,2], [1,3], [4,2]]})

关于python pandas 计算列中列表内的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52624059/

相关文章:

python - 使用 gspread 查找电子表格的 file_id

python - 查找向量中元素的索引

python-3.x - 如何在Python中对没有标题的大型csv信号文件进行分类?

python - 需要将整个列从字符串格式转换为 Dataframe 的日期格式

python - 迭代 Pandas 数据框中的列表并总结其他列

python - 在 Pandas 中跨分组数据框减去值

python - 有没有办法在 Azure 服务总线上发送带有 Python 主题和订阅的文件?

python - 列表索引越界和堆栈溢出错误

python - 添加列参数时,Pandas 数据透视表按字母顺序(错误地)对分类数据进行排序

python-3.x - Pandas 错误: Passing lists with missing labels