带有 If 语句的 Python DataFrames For 循环不起作用

Col*_*uck 1 python for-loop dataframe pandas

我有一个名为 ES_15M_Summary 的数据帧,在标题为 ES_15M_Summary['Rolling_OLS_Coefficient'] 的列中具有系数/beta,如下所示:

“Rolling_OLS_Coefficient”列

如果上图中的列 ('Rolling_OLS_Coefficient') 的值大于 0.08,我希望名为 'Long' 的新列是二进制 'Y'。如果另一列中的值小于 0.08,我希望该值是 'NaN' 或只是 'N'(任何一种都有效)。

所以我正在写一个 for 循环来运行列。首先,我创建了一个名为“Long”的新列并将其设置为 NaN:

ES_15M_Summary['Long'] = np.nan
Run Code Online (Sandbox Code Playgroud)

然后我做了以下 For 循环:

for index, row in ES_15M_Summary.iterrows():
    if ES_15M_Summary['Rolling_OLS_Coefficient'] > .08:
        ES_15M_Summary['Long'] = 'Y'
    else:
        ES_15M_Summary['Long'] = 'NaN'
Run Code Online (Sandbox Code Playgroud)

我收到错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 
Run Code Online (Sandbox Code Playgroud)

...参考上面显示的 if 语句行 (if.​​..>.08:)。我不确定为什么我会收到这个错误或者 for 循环有什么问题。任何帮助表示赞赏。

jez*_*ael 5

我认为更好的是使用numpy.where

mask = ES_15M_Summary['Rolling_OLS_Coefficient'] > .08
ES_15M_Summary['Long'] = np.where(mask, 'Y', 'N')
Run Code Online (Sandbox Code Playgroud)

样本:

ES_15M_Summary = pd.DataFrame({'Rolling_OLS_Coefficient':[0.07,0.01,0.09]})
print (ES_15M_Summary)
   Rolling_OLS_Coefficient
0                     0.07
1                     0.01
2                     0.09

mask = ES_15M_Summary['Rolling_OLS_Coefficient'] > .08
ES_15M_Summary['Long'] = np.where(mask, 'Y', 'N')
print (ES_15M_Summary)
   Rolling_OLS_Coefficient Long
0                     0.07    N
1                     0.01    N
2                     0.09    Y
Run Code Online (Sandbox Code Playgroud)

循环,非常慢的解决方案:

for index, row in ES_15M_Summary.iterrows():
    if ES_15M_Summary.loc[index, 'Rolling_OLS_Coefficient'] > .08:
        ES_15M_Summary.loc[index,'Long'] = 'Y'
    else:
        ES_15M_Summary.loc[index,'Long'] = 'N'
print (ES_15M_Summary)
   Rolling_OLS_Coefficient Long
0                     0.07    N
1                     0.01    N
2                     0.09    Y
Run Code Online (Sandbox Code Playgroud)

时间

#3000 rows
ES_15M_Summary = pd.DataFrame({'Rolling_OLS_Coefficient':[0.07,0.01,0.09] * 1000})
#print (ES_15M_Summary)


def loop(df):
    for index, row in ES_15M_Summary.iterrows():
        if ES_15M_Summary.loc[index, 'Rolling_OLS_Coefficient'] > .08:
            ES_15M_Summary.loc[index,'Long'] = 'Y'
        else:
            ES_15M_Summary.loc[index,'Long'] = 'N'
    return (ES_15M_Summary)

print (loop(ES_15M_Summary))


In [51]: %timeit (loop(ES_15M_Summary))
1 loop, best of 3: 2.38 s per loop

In [52]: %timeit ES_15M_Summary['Long'] = np.where(ES_15M_Summary['Rolling_OLS_Coefficient'] > .08, 'Y', 'N')
1000 loops, best of 3: 555 µs per loop
Run Code Online (Sandbox Code Playgroud)