You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多列字符串出现次数统计问题(无法堆叠DataFrame)

统计DataFrame两列中字符串的总出现次数

先构造示例DataFrame:

import pandas as pd

df = pd.DataFrame({
    'Column1': ['da', 'fa', 'ra', 'ta'],
    'Column2': ['fa', 'da', 'da', 'ta']
})

可以通过以下步骤实现统计需求,无需堆叠列:

  • 分别统计两列的字符串频次:
    col1_counts = df['Column1'].value_counts()
    col2_counts = df['Column2'].value_counts()
    
  • 将两个频次统计结果相加,用fill_value=0处理只在单一列出现的字符串,最后转为整数类型:
    total_counts = col1_counts.add(col2_counts, fill_value=0).astype(int)
    

执行后得到的结果如下:

da    3
fa    2
ta    2
ra    1
dtype: int64

这个方法直接对两列的频次数据进行合并计算,不会生成含空值的新行,完全满足你的要求。

内容的提问来源于stack exchange,提问作者Diogo Bichon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 21:50:41