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

标签 python pandas aggregation

我的时间序列是这样的:

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

类型为“B”时,Volume_B 为聚合交易量;当类型为“S”时,Volume_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)
)

关于python - 根据另一列值重新采样和聚合数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68401257/

相关文章:

python - python的通用捕获

python - 如何使用循环将一行除以前一行的内容

c# - 数据聚合

python - 使用正则表达式 Pandas Dataframe 进行电子邮件验证

python - matplotlib 图中的刻度标签文本和频率

linux - Linux 上的端口聚合

json - 多个聚合Elasticsearch中START_OBJECT的未知 key

python - 有没有办法在pygame中获取 "screenshot",然后将其保存为 Sprite 以降低代码复杂性?

python Selenium : stale element reference: element is not attached to the page document

python - 访问 "module scope"变量