【问题标题】:Pandas get the Month Ending Values from SeriesPandas 从系列中获取月末值
【发布时间】:2023-03-11 10:23:01
【问题描述】:

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

样本数据:

           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 之类的东西来做到这一点?

或者我是否必须执行类似 iterrows 的操作,查找所有每月条目,按日期排序并选择最后一个?

谢谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用GrouperGroupBy.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
    

    【讨论】:

    • 太棒了。我只是想知道是否有类似 .last() 的东西?你在这一切都很棒。非常感谢。
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 2021-07-11
      • 2015-06-13
      相关资源
      最近更新 更多