首页 > 解决方案 > 列之间的减法运算以在数据框中创建新列

问题描述

我当前的数据框:

             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 列的值大于 high_shift 列中的值,我想通过减去列 rows adj close 中的值减去 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:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我能够制作一列 (high _> _ high_shift) 显示何时 high > high_shift 但我不能将此作为通过减去其他列来创建新列的条件

标签: pythondataframe

解决方案


Use numpy.where:

df['new_column'] = np.where(df.High > df.high_shift, (df.High - df.high_shift) * 100, 0)
print(df)

Output

         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

推荐阅读