【问题标题】:pandas rolling sum if criteria is met but criteria is specified in a column如果满足条件但在列中指定了条件,则熊猫滚动总和
【发布时间】:2019-02-15 11:38:23
【问题描述】:

我正在尝试对 1000 行进行滚动求和。我想对每一行的 ClosePrice 介于 ClosePrice_low 和 ClosePrice_high 之间的所有行及其上方的 999 求和。

例如:

滚动计数 1000:检查 0:1000 行,如果在 0.0000189375 和 0.0000185625 之间求和(也就是找到第 1000 行的 ClosePrice_low 和 ClosePrice_high 之间的从 0 到 1000 的所有行,并对 ClosePrice 求和)

滚动计数 1001:检查行 1:1001 并在 0.0000189476 和 0.0000185724 之间求和

在下面这样做不起作用:

tempdf['ClosePrice'][np.where(tempdf['ClosePrice'] < tempdf['ClosePrice_high'] & \
    tempdf['ClosePrice'] > tempdf['ClosePrice_low'],tempdf['ClosePrice'],0)].rolling(1000).sum()

因为它总是引用自身的值,它总是介于高低之间。

另外我的数据框大约有 400 万行,所以我需要快速计算。

任何帮助将不胜感激!

      ClosePrice  ClosePrice_high  ClosePrice_low
1000   0.00001875     0.0000189375    0.0000185625
1001   0.00001876     0.0000189476    0.0000185724
1002   0.00001868     0.0000188668    0.0000184932
1003   0.00001869     0.0000188769    0.0000185031
1004   0.00001864     0.0000188264    0.0000184536
1005   0.00001855     0.0000187355    0.0000183645
1006   0.00001859     0.0000187759    0.0000184041
1007   0.00001862     0.0000188062    0.0000184338
1008   0.00001875     0.0000189375    0.0000185625
1009   0.00001868     0.0000188668    0.0000184932
1010  0.00001867     0.0000188567    0.0000184833
1011  0.00001862     0.0000188062    0.0000184338
1012  0.00001859     0.0000187759    0.0000184041
1013  0.00001867     0.0000188567    0.0000184833
1014  0.00001871     0.0000188971    0.0000185229
1015  0.00001881     0.0000189981    0.0000186219
1016  0.00001879     0.0000189779    0.0000186021
1017  0.00001877     0.0000189577    0.0000185823
1018  0.00001878     0.0000189678    0.0000185922
1019  0.00001875     0.0000189375    0.0000185625

【问题讨论】:

  • 这还不清楚。您的意思是对于第 1000 行,您想在第 1000 行找到从 0 到 1000 之间的所有行 ClosePrice_low 和 ClosePrice_high?还是每行的 ClosePrice 介于 ClosePrice_low 和 ClosePrice_high 之间的所有行?
  • 所有行,其中 ClosePrice 位于 ClosePrice_low 和 ClosePrice_high 之间的每一行及其上方的 999

标签: python pandas numpy vectorization rolling-sum


【解决方案1】:

万一我正确理解了问题:

df['cpl'] = df.ClosePrice_low.rolling(1000).max()
df['cph'] = df.ClosePrice_high.rolling(1000).min()
df = df[(df.ClosePrice <= df.cph) & (df.ClosePrice >= df.cpl)]
df.drop(['cpl', 'cph'], inplace=True)
df.sum()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-07
    • 2018-04-17
    • 2019-09-06
    • 1970-01-01
    • 2020-06-08
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多