首页 > 解决方案 > Pandas 从系列中获取月末值

问题描述

我需要从一系列条目中获取月末余额。

样本数据:

           date     contrib   totalShrs
0    2009-04-23     5220.00   10000.000
1    2009-04-24    10210.00   20000.000
2    2009-04-27    16710.00   30000.000
3    2009-04-30    22610.00   40000.000
4    2009-05-05    28909.00   50000.000
5    2009-05-20    38409.00   60000.000
6    2009-05-28    46508.00   70000.000
7    2009-05-29    56308.00   80000.000
8    2009-06-01    66108.00   90000.000
9    2009-06-02    78108.00  100000.000
10   2009-06-12    86606.00  110000.000
11   2009-08-03    95606.00  120000.000

输出看起来像这样:

2009-04-30   40000
2009-05-31   80000
2009-06-30  110000 
2009-07-31  110000  
2009-08-31  120000

有没有简单的熊猫方法?

我不明白如何使用 groupby 之类的东西来做到这一点?

还是我必须做类似 iterrows 的事情,找到所有每月条目,按日期排序并选择最后一个?

谢谢。

标签: pythonpandas

解决方案


使用Grouperwith ,通过withGroupBy.last前向填充缺失值:ffillSeries.reset_index

#if necessary
#df['date'] = pd.to_datetime(df['date'])

df = df.groupby(pd.Grouper(freq='m',key='date'))['totalShrs'].last().ffill().reset_index()
#alternative
#df = df.resample('m',on='date')['totalShrs'].last().ffill().reset_index()
print (df)
        date  totalShrs
0 2009-04-30    40000.0
1 2009-05-31    80000.0
2 2009-06-30   110000.0
3 2009-07-31   110000.0
4 2009-08-31   120000.0

推荐阅读