【问题标题】:Column of original indices in groupby pandasgroupby pandas中的原始索引列
【发布时间】:2019-01-06 17:19:45
【问题描述】:

我正在使用以下功能:

first_last = df.groupby(['stock', Grouper(freq='D')])['price'].agg(['first','last'])

,它为我提供了一个数据框,其中包含每只股票每天的第一个非 nan 和最后一个非 nan 价格。

能否请您帮帮我,如何在创建的“first_last”df 中添加两列,以便它们包含数据帧“df”的原始索引,从中获取第一个和最后一个值?

原来的df格式如下:

    Index                  price              stock            
2016-10-21 17:00:00        150                 85
2016-10-21 17:30:00        100                 85
2016-10-21 17:00:00         50                 88

-- 我需要在 df "first_last" 中第一个和最后一个价格值的每个值前面都有“索引”。

【问题讨论】:

    标签: python pandas indexing group-by


    【解决方案1】:

    您需要从 DatetimeIndex 创建具有相同缺失值的辅助列,例如 price 列,然后聚合两列:

    df['idx'] = df.index.where(df['price'].notnull(),  np.nan)
    
    first_last = df.groupby(['stock', pd.Grouper(freq='D')])['price', 'idx'].agg(['first','last'])
    first_last.columns = first_last.columns.map('_'.join)
    print (first_last)
                      price_first  price_last           idx_first  \
    stock Index                                                     
    85    2016-10-21          150         100 2016-10-21 17:00:00   
    88    2016-10-21           50          50 2016-10-21 17:00:00   
    
                                idx_last  
    stock Index                           
    85    2016-10-21 2016-10-21 17:30:00  
    88    2016-10-21 2016-10-21 17:00:00  
    

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 2019-02-07
      • 2014-11-15
      • 1970-01-01
      • 2018-08-19
      • 2018-09-22
      相关资源
      最近更新 更多