Apply different functions to different items in group object: Python pandas

后端 未结 3 1737
暗喜
暗喜 2021-02-03 11:46

Suppose I have a dataframe as follows:

In [1]: test_dup_df

Out[1]:
                  exe_price exe_vol flag 
2008-03-13 14:41:07  84.5    200     yes
2008-03-13         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-03 11:54

    Apply your own function:

    In [12]: def func(x):
                 exe_price = (x['exe_price']*x['exe_vol']).sum() / x['exe_vol'].sum()
                 exe_vol = x['exe_vol'].sum()
                 flag = True        
                 return Series([exe_price, exe_vol, flag], index=['exe_price', 'exe_vol', 'flag'])
    
    
    In [13]: test_dup_df.groupby(test_dup_df.index).apply(func)
    Out[13]:
                        exe_price exe_vol  flag
    date_time                                  
    2008-03-13 14:41:07      84.5     200  True 
    2008-03-13 14:41:37        85   10000  True
    2008-03-13 14:41:38      84.5   69700  True
    2008-03-13 14:41:39      84.5    1200  True
    2008-03-13 14:42:00      84.5    1000  True
    2008-03-13 14:42:08      84.5     300  True
    2008-03-13 14:42:10     20.71  100000  True
    2008-03-13 14:42:15      84.5    5000  True
    2008-03-13 14:42:16      84.5    3200  True
    

提交回复
热议问题