根据另一个列值重新采样和聚合数据

Resample and aggregate data according to another column value

我的时间序列是这样的:

TranID,Time,Price,Volume,SaleOrderVolume,BuyOrderVolume,Type,SaleOrderID,SaleOrderPrice,BuyOrderID,BuyOrderPrice
1,09:25:00,137.69,200,200,453,B,182023,137.69,241939,137.69
2,09:25:00,137.69,253,300,453,S,184857,137.69,241939,137.69
3,09:25:00,137.69,47,300,200,B,184857,137.69,241322,137.69
4,09:25:00,137.69,153,200,200,B,219208,137.69,241322,137.69

我想按体积重新采样和聚合数据帧,但结果,我应该能够得到类似的东西:

Time, Volume_B, Volume_S
09:25:00, 400, 253
Type 为 'B' 时,

Volume_B 为聚合卷,当其 Type[] 为 Volume_S 时,为聚合卷=25=] 是 'S'.

我的函数如下所示,但效果不佳。

data.resample('t').agg(Volume_B=(Volume=lambda x: np.where(x['Type']=='B', x['Volume'], 0)), Volume_A=(Volume=lambda x: np.where(x['Type']=='S', x['Volume'], 0)))

如何正确实施?

一种方法是像您一样在 np.where 之前创建列 Volume_B(和 _S),然后聚合,因此:

res = (
    df.assign(Volume_B= lambda x: np.where(x['Type']=='B', x['Volume'], 0), 
              Volume_S= lambda x: np.where(x['Type']=='S', x['Volume'], 0))\
      .groupby(df['Time']) # you can replace by resample here
      [['Volume_B','Volume_S']].sum()
      .reset_index()
)
print(res)
       Time  Volume_B  Volume_S
0  09:25:00       400       253

编辑,使用你的输入(并在时间列上聚合),然后你也可以做一个 pivot_table 比如:

(df.pivot_table(index='Time', columns='Type', 
                values='Volume', aggfunc=sum)
   .add_prefix('Volume_')
   .reset_index()
   .rename_axis(columns=None)
)