【发布时间】: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