python - 列之间的减法运算以在数据框中创建新列
问题描述
我当前的数据框:
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 但我不能将此作为通过减去其他列来创建新列的条件
解决方案
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
推荐阅读
- javascript - 当 iframe 中的表单发生更改时,如何在 chrome 扩展中维护全局变量值?
- html - 单击资源管理器下载弹出窗口上的保存按钮
- c# - 错误 CS0246,unity 找不到命名空间
- scheme - 如何在 DrRacket 中使用家谱创建列表
- php - 使用 brew 安装 Composer 后供应商文件夹丢失
- python - 如何使用 Flask send_file 下载 in-memory-ZIP-FILE 对象
- python - 无需替换数组的快速组合 - NumPy / Python
- c++ - 如何使用 MPI 发送 3D 数组的切片?
- wpf - 如何从 XAML x:Array 中的 ViewModel 访问 const 字符串
- python - PyQt4 - 如何返回和保存所选目录的路径