创建一个“定向”pandas pct_change函数

问题描述 投票:0回答:1

我想创建一个方向性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 dataframe列时,如下所示: 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

python pandas math percentage
1个回答
2
投票

由于@Wen说多处,不太可能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

© www.soinside.com 2019 - 2024. All rights reserved.