假设我们在 pandas 中有一个数据框,如下所示:
col1 | col2 | col3 | col4
22 | Nan | 23 | 56
12 | 54 | 22 | 36
48 | Nan | 2 | 45
76 | 32 | 13 | 6
23 | Nan | 43 | 8
67 | 54 | 56 | 64
16 | 32 | 32 | 6
3 | 54 | 64 | 8
67 | 4 | 23 | 64
我想替换的值col4
with col1
if col4<col1
and col2
is not NaN
所以结果应该是
col1 | col2 | col3 | col4
22 | Nan | 23 | 56
12 | 54 | 22 | 36
48 | Nan | 2 | 45
76 | 32 | 13 | 76
23 | Nan | 43 | 8
67 | 54 | 56 | 67
16 | 32 | 32 | 16
3 | 54 | 64 | 8
67 | NaN | 23 | 64
我尝试了以下代码
df.loc[((df['col4'] < df['col1']) & (pd.notnull(df['col2']))), ['col4']] = df.loc['col1']
问题出在等号之后。有谁知道如何解决这个问题?
用这个:
df.loc[(df['col1']>df['col4'])&(df['col2'].notnull()),'col4']=df['col1']
And now:
print(df)
Is:
col1 col2 col3 col4
0 22 NaN 23 56
1 12 54.0 22 36
2 48 NaN 2 45
3 76 32.0 13 76
4 23 NaN 43 8
5 67 54.0 56 67
6 16 32.0 32 16
7 3 54.0 64 8
8 67 4.0 23 67
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)