Col*_*uck 5 python loops shift dataframe pandas
我有一个数据框,Df2. 我正在尝试检查下面一列的最后 10 行中的每一行Lead_Lag- 如果这些行中的任何一行中除了 null 之外还有任何值,那么我想要一个新列Position等于'Y':
def run_HG_AUDUSD_15M_Aggregate():
Df1 = pd.read_csv(max(glob.iglob(r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Pairs Trading\HG_AUDUSD\CSV\15M\Lead_Lag\*.csv"), key=os.path.getctime))
Df2 = Df1[['Date', 'Close_HG', 'Close_AUDUSD', 'Lead_Lag']]
Df2['Position'] = ''
for index,row in Df2.iterrows():
if Df2.loc[Df2.index.shift(-10):index,"Lead_Lag"].isnull():
continue
else:
Df2.loc[index, 'Position'] = "Y"
Run Code Online (Sandbox Code Playgroud)
数据样本如下:
def run_HG_AUDUSD_15M_Aggregate():
Df1 = pd.read_csv(max(glob.iglob(r"C:\Users\cost9\OneDrive\Documents\PYTHON\Daily Tasks\Pairs Trading\HG_AUDUSD\CSV\15M\Lead_Lag\*.csv"), key=os.path.getctime))
Df2 = Df1[['Date', 'Close_HG', 'Close_AUDUSD', 'Lead_Lag']]
Df2['Position'] = ''
for index,row in Df2.iterrows():
if Df2.loc[Df2.index.shift(-10):index,"Lead_Lag"].isnull():
continue
else:
Df2.loc[index, 'Position'] = "Y"
Run Code Online (Sandbox Code Playgroud)
因此,在这种情况下,我希望新列的最后两个值与该列中至少最后 10 行之一的值相同Position。我想滚动应用它 - 例如第 13 行“位置”值将查看第 12-3 行,第 12 行“位置”值将查看第 11-2 行,等等。'Y'Lead_Lag
相反,我收到错误:
NotImplementedError:不支持类型 RangeIndex
我已经尝试了移位方法的几种变体(在循环之前定义等),但无法使其工作。
编辑:这是解决方案:
N = 10
Df2['Position'] = ''
for index,row in Df2.iterrows():
if (Df2.loc[index-N:index,"Lead_Lag"] != "N").any():
Df2.loc[index, 'Position'] = "Y"
else:
Df2.loc[index, 'Position'] = "N"
Run Code Online (Sandbox Code Playgroud)
编辑:
在发布有问题的解决方案后,我发现OP需要其他东西 - 测试窗口N,所以添加了另一个答案。
旧的解决方案:
numpy.where通过链接与布尔掩码一起使用:
m = df["Lead_Lag"].notnull() & df.index.isin(df.index[-10:])
Run Code Online (Sandbox Code Playgroud)
或者通过按位置选择列并iloc添加Falses by reindex:
m = df["Lead_Lag"].iloc[-10:].notnull().reindex(df.index, fill_value=False)
Run Code Online (Sandbox Code Playgroud)
df['new'] = np.where(m, 'Y', '')
print (df)
Date Close_HG Close_AUDUSD Lead_Lag new
0 7/19/2017 12:59 2.70 0.7956 NaN
1 7/19/2017 13:59 2.70 0.7955 NaN
2 7/19/2017 14:14 2.70 0.7954 NaN
3 7/20/2017 3:14 2.70 0.7910 NaN
4 7/20/2017 5:44 2.70 0.7910 NaN
5 7/20/2017 7:44 2.71 0.7925 NaN
6 7/20/2017 7:59 2.70 0.7924 NaN
7 7/20/2017 8:44 2.70 0.7953 Short_Both Y
8 7/20/2017 10:44 2.71 0.7964 Short_Both Y
9 7/20/2017 11:14 2.71 0.7963 Short_Both Y
10 7/20/2017 11:29 2.71 0.7967 Short_Both Y
11 7/20/2017 13:14 2.71 0.7960 Short_Both Y
12 7/20/2017 13:29 2.71 0.7956 Short_Both Y
13 7/20/2017 14:29 2.71 0.7957 Short_Both Y
Run Code Online (Sandbox Code Playgroud)