python - 使用逻辑 True/False 聚合重新采样 Pandas DataFrame

标签 python pandas aggregate resampling

很抱歉,如果标题不是很清楚,但我想不出一个好的方法来构建它。

我想在每天重新采样 DataFrame 时执行一些高级逻辑。

所以我有一个名为 trades 的 DataFrame,如下所示:

                         agg_tradeid    price  quantity  fst_tradeid  \
timestamp                                                              
2017-12-08 06:03:13.653            0  0.00023     100.0            0   
2017-12-08 06:08:00.292            1  0.00030    1999.0            1   
2017-12-08 06:09:05.218            2  0.00035    3339.0            2   
2017-12-08 06:09:17.911            3  0.00035     206.0            3   
2017-12-08 06:10:13.633            4  0.00033    1533.0            4   

                         lst_tradeid      timestamp     buy best_price  
timestamp                                                               
2017-12-08 06:03:13.653            0  1512712993653    True       True  
2017-12-08 06:08:00.292            1  1512713280292    True       True  
2017-12-08 06:09:05.218            2  1512713345218   False       True  
2017-12-08 06:09:17.911            3  1512713357911   False       True  
2017-12-08 06:10:13.633            4  1512713413633   False       True  

我想以某种复杂的方式重新采样为每日('1D')。

  • 价格:ohlc
  • 数量:总和
  • 创建一个新列,ract,它将是数量,其中buy==True除以总重采样数量 表示 1D

最后一点给我带来了麻烦,我可以简单地用以下方法完成其他两点:

trades.resample('1D').agg({'price':'ohlc', 'quantity':'sum'})

最佳答案

您可以使用临时变量单独计算 ract 并将结果赋回:

i = df.assign(v=df.quantity.where(df.buy))\
      .resample('1D')[['v', 'quantity']]\
      .sum()

j = df.resample('1D').agg({'price':'ohlc', 'quantity':'sum'})
j['ract'] = i.v / i.quantity

j

              price                            quantity      ract
               open     high      low    close quantity          
timestamp                                                        
2017-12-08  0.00023  0.00035  0.00023  0.00033   7177.0  0.292462

关于python - 使用逻辑 True/False 聚合重新采样 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48774824/

相关文章:

python - 使用 = 分配变量无法正常工作

python - 跨多列实现 Django 2.2 数据库约束

python - 访问时自动创建(并保留)一个对象

python - 将数据从一行移动到一组指定行中的另一行

python - 当单元格内容是列表时从单元格中删除元素

r - 按组提取变量最小值对应的行

python - Python 中的产量

r - 如何在R中聚合分类数据?

domain-driven-design - 您使用什么方法来识别域驱动设计中的聚合根?

Python seaborn 与散点图和 Pandas 的错误