【问题标题】:calculate total events in month using pandas使用 pandas 计算月份的总事件
【发布时间】:2014-01-07 07:47:32
【问题描述】:

我有使用 groupby(Code, ID, Date) 的数据框,如下所示 -

Code    ID  Date              Sum
100 200 2012-05-31   50
                2012-06-07   60
                2012-06-25   70
                2012-06-26   80
                2013-06-27   85
                2013-06-28   90

我想创建一个数据框,它可以使用 groupby(代码、ID、月/年)显示数据 -

Code    ID     Month/Year     Sum
100     200    May/2012        50
               June/2012       210
               June/2013       175

请指教

【问题讨论】:

标签: python pandas


【解决方案1】:

您可以对每个组进行每月resample

因此首先将“日期”列转换为日期时间:

df['Date'] = pd.to_datetime(df['Date'])

然后将其设置为索引,groupby 在['Code', 'ID'] 上,然后在每个组上应用resample

df.set_index('Date').groupby(['Code', 'ID']).resample('M', 'sum')

In [6]: df = pd.DataFrame({'Code':100, 'ID':200, 'Date':pd.date_range("2012-01-01", periods=10, freq='10D'), 'Sum':np.random.randint(10, size=10)})

In [7]: df
Out[7]:
   Code                Date   ID  Sum
0   100 2012-01-01 00:00:00  200    1
1   100 2012-01-11 00:00:00  200    9
2   100 2012-01-21 00:00:00  200    5
3   100 2012-01-31 00:00:00  200    9
4   100 2012-02-10 00:00:00  200    8
5   100 2012-02-20 00:00:00  200    3
6   100 2012-03-01 00:00:00  200    9
7   100 2012-03-11 00:00:00  200    8
8   100 2012-03-21 00:00:00  200    3
9   100 2012-03-31 00:00:00  200    5

In [8]: df.set_index('Date').groupby(['Code', 'ID']).resample('M', 'sum')
Out[8]:
                     Code   ID  Sum
Code ID  Date
100  200 2012-01-31   400  800   24
         2012-02-29   200  400   11
         2012-03-31   400  800   25

要绘制它,应该这样做:

fig, ax = plt.subplots()

for name, group in df.set_index('Date').groupby(['Code', 'ID']):
    group['Sum'].resample('M', 'sum').plot(ax=ax, label=name)

但您也可以进一步处理您的结果,“unstack”(将索引级别带到列)然后绘图:

df2 = df.set_index('Date').groupby(['Code', 'ID']).resample('M', 'sum')
df2['Sum'].unstack([0,1]).plot()

【讨论】:

  • 谢谢,有没有办法使用 matplotlib 将上述数据绘制为时间序列图,x 轴为日期,y 轴为 Sum 为每个 ID 使用 matplotlib?
  • 每个代码/ID 单独一行?
  • 在提出的解决方案上仍然面临问题。
  • 面对发行人,数据框 (df_final) 如下所示 -
    Code,ID,Date,Code1,Amt1,Code2,Amt2,Code3,Sum 195,10000 - XXX,2012-05-31 00:00:00,40,0.0,180,0.0,780,107970824.0 195,10000 - XXX,2012-06-30 00:00:00,10,0.0,45,0.0,195,8180645.0 195,10000 - XXX ,2012-07-31 00:00:00,10,0.0,45,0.0,195,2600000.0 275,30465 - XXX,2012-05-31 00:00:00,10,0.0,45,0.0,275, 283905693.0 275,30465 - XXX,2012-06-30 00:00:00,10,0.0,45,0.0,275,75113236.0 我正在绘制 as-df_final['Sum'].unstack([0,1]) .plot() 抛出错误 - TypeError: an integer is required
  • 使用 fillna('0') 将 NaN 替换为 0。问题已解决
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 2016-12-17
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多