我目前dataframe:
Adj Close High high_shift high_>_high
Date
2017-01-03 14.676315 15.65 14.70 True
2017-01-04 14.676315 15.68 15.65 True
2017-01-05 14.913031 15.91 15.68 True
2017-01-06 14.827814 15.92 15.91 True
2017-01-09 14.515349 15.60 15.92 False
2017-01-10 14.657379 15.68 15.60 True
2017-01-11 14.827814 15.68 15.68 False
2017-01-12 15.055059 16.25 15.68 True
2017-01-13 14.846750 15.95 16.25 False
2017-01-16 14.913031 15.75 15.95 False
如果高列的值是比high_shift列中的值越大,我想从列列从high_shift * 100列形容词收盘价减去行值减去值来创建一个新列。
刚刚例如:
if (df.High > df.high_shift):
df['new_column'] = (df['Adj Close'] - df['high_shift'])*100
如果高列的值不低于high_shift列的值越大,我想新的列行中的值是0
我想下面的代码行,但我得到的错误,我甚至不能打印结果:
for i in df['high_>_high'], df['Close'], df['high_shift']:
if df['high_>_high'][i]:
(df['Close'][i] - df['high_shift'][i])*100
ValueError异常:一个系列的真值是不明确的。使用a.empty,a.bool(),a.item(),a.any()或a.all()。
我是能够使表示柱(高_> _ high_shift)时高> high_shift但我不能通过这个作为条件减去其他人创建新列
分析解答
使用numpy.where:
df['new_column'] = np.where(df.High > df.high_shift, (df.High - df.high_shift) * 100, 0)
print(df)
产量
Date Adj Close High high_shift high_>_high new_column
0 2017-01-03 14.676315 15.65 14.70 True 95.0
1 2017-01-04 14.676315 15.68 15.65 True 3.0
2 2017-01-05 14.913031 15.91 15.68 True 23.0
3 2017-01-06 14.827814 15.92 15.91 True 1.0
4 2017-01-09 14.515349 15.60 15.92 False 0.0
5 2017-01-10 14.657379 15.68 15.60 True 8.0
6 2017-01-11 14.827814 15.68 15.68 False 0.0
7 2017-01-12 15.055059 16.25 15.68 True 57.0
8 2017-01-13 14.846750 15.95 16.25 False 0.0
9 2017-01-16 14.913031 15.75 15.95 False 0.0