我的数据框中有以下列:
W1 W2 W3 W4 L1 L2 L3 L4
0 6 6 3 6 7 3 6
7 Nan Nan Nan 6 Nan Nan Nan
我想向这个数据框添加四列,SET1 .. SET4,它们是:
- 1.0 如果 Wi > Li 而 Nan 都不是
- 0.0 如果 Wi < Li 且 Nan 都不是
- nan 如果 Wi 或 Li 是 Nan
在上面的例子中,输出应该是:
SET1 SET2 SET3 SET4
0.0 0.0 1.0 0.0
1.0 Nan Nan Nan
我使用以下代码来应用前 2 个项目符号,但我很难正确处理 NaN。
for i in range(1,5):
wincol = "W" + str(i)
losecol = "L" + str(i)
setcol = "SET" + str(i)
matches_df[setcol] = matches_df[wincol] > matches_df[losecol]
matches_df[setcol] = matches_df[setcol].astype(float)
请您参考如下方法:
您将需要 startswith ,然后只需划分值,并创建您需要的 df
#df=df.replace('Nan',np.nan)
#df=df.astype(float)
new_df=pd.DataFrame((df.loc[:,df.columns.str.startswith('W')].values/df.loc[:,df.columns.str.startswith('L')].values))
new_df[new_df.notnull()]=new_df.gt(1).astype(int)
new_df
Out[239]:
0 1 2 3
0 0.0 0.0 1.0 0.0
1 1.0 NaN NaN NaN
