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

如何遍历DataFrame统计各月份每个值的出现次数?

解决方案

首先修正你原始数据的小问题(字典未闭合、字符串需加引号),然后可以通过两种简洁的方式实现需求:

方法一:列遍历+统一索引

import pandas as pd

# 修正后的原始数据
data = {
    'Jan 2018': ['a', 'a', 'b', 'c', 'd', 'd'],
    'Feb 2018': ['a', 'b', 'd', 'e', 'e', 'f']
}
df = pd.DataFrame(data)

# 收集所有出现过的字母作为统一索引
all_letters = pd.concat([df[col] for col in df.columns]).unique()

# 生成目标DataFrame:按字母索引,各月份为列,值为对应出现次数
df2 = pd.DataFrame({
    col: df[col].value_counts().reindex(all_letters, fill_value=0)
    for col in df.columns
})

print(df2)

输出结果:

Jan 2018  Feb 2018
a         2         1
b         1         1
c         1         0
d         2         1
e         0         2
f         0         1

方法二:长格式转换+透视表(更简洁)

这种方法逻辑直观,对新手更友好:

import pandas as pd

data = {
    'Jan 2018': ['a', 'a', 'b', 'c', 'd', 'd'],
    'Feb 2018': ['a', 'b', 'd', 'e', 'e', 'f']
}
df = pd.DataFrame(data)

# 将宽格式数据转为长格式:合并月份列为单独一列,对应字母列
melted_df = df.melt(var_name='Month', value_name='Letter')

# 透视表统计:按字母分组,各月份为列,统计出现次数,缺失值补0
df2 = melted_df.pivot_table(index='Letter', columns='Month', aggfunc='size', fill_value=0)

print(df2)

绘制柱状图

生成的df2可以直接用于绘制柱状图:

import matplotlib.pyplot as plt

df2.plot(kind='bar', figsize=(8, 5))
plt.xlabel('Letters')
plt.ylabel('Occurrence Count')
plt.title('Monthly Letter Occurrence Statistics')
plt.legend(title='Month')
plt.show()

内容的提问来源于stack exchange,提问作者Alfie Davies

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:54:30