假设我有这样一个数据帧:
id openPrice closePrice
1 10.0 13.0
2 20.0 15.0
我想添加另一个名为“移动”的列: 如果openprice<;close price设置为1,则else设置为-1
输出应为:
id openPrice closePrice movement
1 10.0 13.0 1
2 20.0 15.0 -1
我可以在for循环中完成,但是对于一个有10000000行以上的df来说,这会很耗时。你知道吗
我是python新手,不知道有没有python函数可以有效地实现这一点。你知道吗
谢谢
在
pandas
中实现快速性能的关键是使用向量化操作,即避免(正如您所注意的)缓慢的Python循环的内置操作。你知道吗我比较喜欢的方法是对这样的更改进行标记,即对差异调用
np.sign
(当然,首先要做import numpy as np
):这样做的一个好处是,如果
openPrice == closePrice
,您会自动获得movement == 0
,这非常方便。你知道吗如果你更喜欢手工操作,你可以做向量运算,比如
因为这里有
False == 0
和True == 1
,但是你必须有特殊情况closePrice == openPrice
。你知道吗可以使用
where
设置设置值的条件,最后一个参数是条件为False
时的值:相关问题 更多 >
编程相关推荐