gpt4 book ai didi

python - 如何在 python 中为数据框添加另一个类似标签的列?

转载 作者:行者123 更新时间:2023-11-28 22:48:29 25 4
gpt4 key购买 nike

假设我有一个这样的数据框:

id      openPrice       closePrice
1 10.0 13.0
2 20.0 15.0

我想添加另一个名为“运动”的列:如果开盘价 < 收盘价设置为 1,否则设置为 -1

输出应该是这样的:

id      openPrice       closePrice    movement
1 10.0 13.0 1
2 20.0 15.0 -1

我可以在 for 循环中执行此操作,但对于具有超过 10,000,000 行的 df 来说会很耗时。

我是 python 的新手,不知道是否有任何 python 函数可以有效地执行此操作。

谢谢

最佳答案

pandas 中实现快速性能的关键是使用矢量化操作,即避免(正如您所注意到的)慢速 Python 循环的内置操作。

我首选的标记更改的方法是在差异上调用 np.sign(当然,首先完成了 import numpy as np):

>>> df
id openPrice closePrice
0 1 10 13
1 2 20 15
>>> df["movement"] = np.sign(df["closePrice"] - df["openPrice"])
>>> df
id openPrice closePrice movement
0 1 10 13 1
1 2 20 15 -1

这样做的一个好处是,如果 openPrice == closePrice,您会自动获得 movement == 0,这很方便。

如果你更喜欢手动做事,你可以像这样做向量运算

>>> df["closePrice"] > df["openPrice"]
0 True
1 False
dtype: bool
>>> (df["closePrice"] > df["openPrice"]) * 2 - 1
0 1
1 -1
dtype: int64

因为这里 False == 0True == 1,但是你必须特殊情况 closePrice == openPrice .

关于python - 如何在 python 中为数据框添加另一个类似标签的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25069201/

25 4 0