【发布时间】:2018-07-26 07:46:13
【问题描述】:
有没有更好的方法(性能方面)在 pandas 中执行以下循环(假设 df 是 DataFrame)?
for i in range(len(df)):
if df['signal'].iloc[i] == 0: # if the signal is negative
if df['position'].iloc[i - 1] - 0.02 < -1: # if the row above - 0.1 < -1 set the value of current row to -1
df['position'].iloc[i] = -1
else: # if the new col value above -0.1 is > -1 then subtract 0.1 from that value
df['position'].iloc[i] = df['position'].iloc[i - 1] - 0.02
elif df['signal'].iloc[i] == 1: # if the signal is positive
if df['position'].iloc[i - 1] + 0.02 > 1: # if the value above + 0.1 > 1 set the current row to 1
df['position'].iloc[i] = 1
else: # if the row above + 0.1 < 1 then add 0.1 to the value of the current row
df['position'].iloc[i] = df['position'].iloc[i - 1] + 0.02
我将不胜感激任何建议,因为我刚刚开始通过 Pandas 路线,显然,可能会错过一些重要的事情。
来源 CSV 数据:
Date,sp500,sp500 MA,UNRATE,UNRATE MA,signal,position
2000-01-01,,,4.0,4.191666666666665,1,0
2000-01-02,,,4.0,4.191666666666665,1,0
2000-01-03,102.93,95.02135,4.0,4.191666666666665,1,0
2000-01-04,98.91,95.0599,4.0,4.191666666666665,1,0
2000-01-05,99.08,95.11245000000001,4.0,4.191666666666665,1,0
2000-01-06,97.49,95.15450000000001,4.0,4.191666666666665,1,0
2000-01-07,103.15,95.21575000000001,4.0,4.191666666666665,1,0
2000-01-08,103.15,95.21575000000001,4.0,4.191666666666665,1,0
2000-01-09,103.15,95.21575000000001,4.0,4.191666666666665,1,0
期望的输出:
Date,sp500,sp500 MA,UNRATE,UNRATE MA,signal,position
2000-01-01,,,4.0,4.191666666666665,1,0.02
2000-01-02,,,4.0,4.191666666666665,1,0.04
2000-01-03,102.93,95.02135,4.0,4.191666666666665,1,0.06
2000-01-04,98.91,95.0599,4.0,4.191666666666665,1,0.08
2000-01-05,99.08,95.11245000000001,4.0,4.191666666666665,1,0.1
2000-01-06,97.49,95.15450000000001,4.0,4.191666666666665,1,0.12
2000-01-07,103.15,95.21575000000001,4.0,4.191666666666665,1,0.14
2000-01-08,103.15,95.21575000000001,4.0,4.191666666666665,1,0.16
2000-01-09,103.15,95.21575000000001,4.0,4.191666666666665,1,0.18
更新下面的所有答案(在我写这篇文章的那一刻)都会产生常量 position 0.02 值,这与我的幼稚循环方法不同。
换句话说,我正在寻找一种解决方案,它可以为position 列提供0.02、0.04、0.06、0.08 等。
【问题讨论】:
-
如果你用 pandas 循环,你几乎总是做错了
-
@SuperStew 是的,我有这样的直觉
-
你能添加输入和期望输出的例子吗?类似minimal reproducible example.
-
@varnie:大多数人错过的是输出的第 n 行不依赖于 输入 的第 n-1 行,而是第 n-1 行输出的行,因此不能简单地分解为班次。
-
如果您有一个包含简单循环的有效解决方案,请创建一个仅依赖于 numpy 数组的解决方案,如 @Jonas Byström 所做的,然后使用像 Numba 或 Cython 这样的编译器。例如。 stackoverflow.com/a/50969037/4045774
标签: python performance pandas