Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python groupby中的原始索引列_Python_Pandas_Indexing_Group By - Fatal编程技术网

Python groupby中的原始索引列

Python groupby中的原始索引列,python,pandas,indexing,group-by,Python,Pandas,Indexing,Group By,我正在使用以下函数: first_last = df.groupby(['stock', Grouper(freq='D')])['price'].agg(['first','last']) ,它为我提供了一个数据帧,其中包含每只股票每天的第一个非nan和最后一个非nan价格 你能告诉我,我怎样才能在创建的“first_last”df中添加两列,以便它们包含数据帧“df”的原始索引,从中获取第一个和最后一个值 原始df的形式如下: Index pric

我正在使用以下函数:

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

您需要从
DatetimeIndex
创建具有相同缺失值(如
price
列)的helper列,然后聚合这两列:

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