熊猫从系列中获得月末值

时间:2019-04-14 06:33:11

标签: python 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

有没有简单的Pandas方法?

我看不到如何使用groupby来做到这一点?

还是我需要做类似迭代的事情,查找所有每月条目,按日期排序并选择最后一个?

谢谢。

2 个答案:

答案 0 :(得分:1)

GrouperGroupBy.last一起使用,将python3.7 /users/philipedwards/Documents/ex15.py test.txt Series.reset_index一起填充缺失值:

ffill

答案 1 :(得分:0)

以下格式可为您提供所需的信息,即月末值,尽管格式与您要求的格式不完全相同:

df['month'] = df['date'].str.split('-', expand = True)[1]   # split date column to get month column
newdf = pd.DataFrame(columns=df.columns) # create a new dataframe for output
grouped = df.groupby('month') # get grouped values
for g in grouped:  # for each group, get last row
    gdf = pd.DataFrame(data=g[1])
    newdf.loc[len(newdf),:] = gdf.iloc[-1,:]  # fill new dataframe with last row obtained
newdf = newdf.drop('date', axis=1)  # drop date column, since month column is there
print(newdf)

输出:

  contrib totalShrs month
0   22610     40000    04
1   56308     80000    05
2   86606    110000    06
3   95606    120000    08
相关问题