基于Python的group by与sum操作实现Year-Txns绘图
绘制年份与交易数关系图的解决方案
嘿,我来帮你搞定这个年份和交易数的图表绘制问题!先理清楚我们手里的数据和需要修正的地方:
原始数据集(dataset1)
这是你提供的初始数据:
| WeekDay | Day | Month | Year | Time | Txns |
|---|---|---|---|---|---|
| 1 | 5 | 1 | 2015 | 3 | 1 |
| 1 | 5 | 1 | 2015 | 4 | 4 |
| 1 | 5 | 1 | 2015 | 5 | 1 |
| 1 | 5 | 1 | 2015 | 7 | 2 |
聚合后的数据集(plot)
经过groupby(['Year', 'Month'])求和后的数据:
| Index | Txns |
|---|---|
| (2014, 12) | 5786 |
| (2015, 1) | 70828 |
| (2015, 2) | 63228 |
| (2015, 3) | 74320 |
代码修正与完整绘图方案
你原来的代码里plot_df = plot.unstack('Month').loc[:, 'Txns']有问题——unstack之后列是月份,索引是年份,根本没有Txns这个列,所以会报错。下面给你两种常用的绘图方案:
方案1:绘制年月时间序列的交易数变化图
适合展示每个月的交易数随时间的趋势:
import pandas as pd import matplotlib.pyplot as plt # 假设dataset1已经是加载好的DataFrame plot = dataset1.groupby(['Year', 'Month'])['Txns'].sum() # 把多级索引转换成可用于绘图的时间格式 plot_df = plot.reset_index() # 构造完整日期(每个月的1号) plot_df['Date'] = pd.to_datetime(plot_df[['Year', 'Month']].assign(Day=1)) # 绘制折线图 plt.figure(figsize=(10, 6)) plt.plot(plot_df['Date'], plot_df['Txns'], marker='o', linestyle='-', color='#1f77b4') plt.title('Monthly Transaction Volume Over Time', fontsize=14) plt.xlabel('Date', fontsize=12) plt.ylabel('Total Transactions', fontsize=12) plt.grid(alpha=0.3) plt.xticks(rotation=45) plt.tight_layout() # 自动调整布局,避免标签被截断 plt.show()
方案2:绘制按年份汇总的交易数对比图
如果只需要看每年的总交易数,用这个方案:
import pandas as pd import matplotlib.pyplot as plt # 按年份汇总交易数 yearly_total = dataset1.groupby('Year')['Txns'].sum() # 绘制柱状图 plt.figure(figsize=(8, 5)) yearly_total.plot(kind='bar', color='#ff7f0e', edgecolor='black') plt.title('Annual Total Transactions', fontsize=14) plt.xlabel('Year', fontsize=12) plt.ylabel('Total Transactions', fontsize=12) plt.xticks(rotation=0) # 年份标签水平显示 plt.tight_layout() plt.show()
这两种方案都能清晰展示年份与交易数的关系,你可以根据需求选择~
内容的提问来源于stack exchange,提问作者Swapnil Shankar
相关产品推荐
相关产品推荐

