【问题标题】:Plotting in python using group by and sum在 python 中使用 group by 和 sum 绘图
【发布时间】:2018-09-16 23:25:29
【问题描述】:

我正在尝试使用以下数据绘制图表。我需要图表 Year vs 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

这是group by和sum之后的数据,在代码中是plot=

Index       Txns
(2014, 12)  5786
(2015, 1)   70828
(2015, 2)   63228
(2015, 3)   74320

我的代码:

plot = dataset1.groupby(['Year', 'Month'])['Txns'].sum()
plot_df = plot.unstack('Month').loc[:, 'Txns']
plot_df.index = pd.PeriodIndex(plot_df.index.tolist(), freq='2015')
plot_df.plot()

我每次都会收到这个错误:

KeyError: '标签 [Txns] 不在 [列] 中'

我该如何解决这个问题?

【问题讨论】:

    标签: python


    【解决方案1】:

    如果您想按年份分组并求和 Txns,为什么不只使用 data.groupby('Year').Txns.sum()

    如果你想绘制它,.plot()

    或年线:

    【讨论】:

    • 感谢您的回复。我实际上希望为每年绘制 3 个不同的折线图,显示 y 轴上的 txns 和 x 轴上的月份
    • 你可以建立一个pivot_table 并绘制它。 pvt = pd.pivot_table(data, columns='Year', index=['Month'], aggfunc='sum', values='Txns') 然后 pvt.plot() 但要注意列中的 NaN 值
    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多