Reputation: 41
I have a data frame, with columns col1
, col2
, and col3
. I would like to replace col2
with the value of col3
if col3
is not null; otherwise, skip the row.
input
col1 col2 col3
1 2 nan
4 5 nan
6 7 8
1 0 9
output
col1 col2 col3
1 2 nan
4 5 nan
6 8 8
1 9 9
This is my code:
for i, row in df.iterrows():
if row['col3'] != np.nan:
row['col2'] = row['col3']
else:
row['col2'] = row['col2']
But it doesn't work.
Upvotes: 1
Views: 654
Reputation:
Use .loc
and .notna()
:
df.loc[df['col3'].notna(), 'col2'] = df['col3']
Output:
>>> df
col1 col2 col3
0 1 2.0 NaN
1 4 5.0 NaN
2 6 8.0 8.0
3 1 9.0 9.0
Upvotes: 2