【问题标题】:Create a "directional" pandas pct_change function创建一个“定向”熊猫 pct_change 函数
【发布时间】:2018-06-13 18:29:19
【问题描述】:

我想创建一个定向 pandas pct_change 函数,因此前一行中的负数,随后一行中较大的负数将导致 pct_change 为负(而不是正)。

我创建了以下函数: ```

ef pct_change_directional(x):
    if x.shift() > 0.0:
        return x.pct_change() #compute normally if prior number > 0

elif x.shift() < 0.0 and x > x.shift:
    return abs(x.pct_change()) # make positive

elif x.shift() <0.0 and x < x.shift():
    return -x.pct_change() #make negative
else:
    return 0

```

但是,当我将它应用到我的 pandas 数据框列时,如下所示: df['col_pct_change'] = pct_change_directional(df[col1]) 我收到以下错误: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

有什么想法可以让我完成这项工作吗?

谢谢! CWE

【问题讨论】:

  • 这可以通过使用多个np.where来解决...
  • @Wen 到底怎么样?

标签: python pandas math percentage


【解决方案1】:

正如@Wen 所说的多个where,不太可能np.select

mask1 = df[col].shift() > 0.0
mask2 = ((df[col].shift() < 0.0) & (df[col] > df[col].shift())
mask3 = ((df[col].shift() < 0.0) & (df[col] < df[col].shift())

np.select([mask1, mask2, mask3],
          [df[col].pct_change(), abs(df[col].pct_change()),
           -df[col].pct_change()],
           0)

关于选择以及在哪里可以看到here 的更多详细信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 2015-03-28
    • 2021-04-10
    • 2013-09-25
    • 2014-05-22
    • 2017-08-30
    • 2022-09-24
    相关资源
    最近更新 更多