Python Groupby MultiIndex

时间:2018-12-03 14:26:41

标签: python pandas dataframe group-by multi-index

我有一个这样的数据框

Original DataFrame

如何添加一个索引和groupby,如:

Desired Output DataFrame

非常感谢!

1 个答案:

答案 0 :(得分:1)

IIUC,您可以尝试以下方法:

df = pd.DataFrame({'Date':['11/1/2018']*5+['11/2/2018']*5,
                   'Stock':['AAPL','SHOP','FB','F','C']*2, 
                   'Price':np.random.randint(20,75,10)})

df['Date'] = pd.to_datetime(df['Date'])

df.set_index(df['Date'], append=True)\
  .rename_axis(['Index','DateGroup'], axis=0)\
  .swaplevel(0,1)\
  .sort_index()

输出:

                       Date Stock  Price
DateGroup  Index                        
2018-11-01 0     2018-11-01  AAPL     26
           1     2018-11-01  SHOP     21
           2     2018-11-01    FB     65
           3     2018-11-01     F     55
           4     2018-11-01     C     47
2018-11-02 5     2018-11-02  AAPL     45
           6     2018-11-02  SHOP     67
           7     2018-11-02    FB     24
           8     2018-11-02     F     52
           9     2018-11-02     C     47