Groupby Pandas中的原始索引列

时间:2018-07-30 12:44:28

标签: python pandas indexing group-by

我正在使用以下功能:

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

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

请问您能不能帮助我,如何将两列添加到创建的“ first_last” df中,以便它们包含数据帧“ df”的原始索引,并从中提取first&last值?

原始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”中第一个和最后一个价格值的每个值前面都有“ Index”。

1 个答案:

答案 0 :(得分:0)

您需要从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