将不同的函数应用于组对象中的不同项:Python pandas

kun*_*omo 10 python group-by function apply pandas

假设我有一个如下数据帧:

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 14:41:37  85.0    10000   yes
2008-03-13 14:41:38  84.5    69700   yes
2008-03-13 14:41:39  84.5    1200    yes
2008-03-13 14:42:00  84.5    1000    yes
2008-03-13 14:42:08  84.5    300     yes
2008-03-13 14:42:10  84.5    88100   yes
2008-03-13 14:42:10  84.5    11900   yes
2008-03-13 14:42:15  84.5    5000    yes
2008-03-13 14:42:16  84.5    3200    yes 
Run Code Online (Sandbox Code Playgroud)

我想组在时间重复的数据14:42:10和应用不同的功能,以exe_priceexe_vol(例如,求和exe_vol的和计算体积加权平均exe_price).我知道我能做到

In [2]: grouped = test_dup_df.groupby(level=0)
Run Code Online (Sandbox Code Playgroud)

将重复索引分组然后使用first()last()函数来获取第一行或最后一行,但这不是我想要的.

有没有办法分组,然后将不同的(由我编写)函数应用于不同列中的值?

wai*_*kuo 14

应用您自己的功能:

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
Run Code Online (Sandbox Code Playgroud)


ask*_*han 1

不太熟悉pandas,但在纯 numpy 中你可以这样做:

tot_vol = np.sum(grouped['exe_vol'])
avg_price = np.average(grouped['exe_price'], weights=grouped['exe_vol'])
Run Code Online (Sandbox Code Playgroud)