Issue
I've got a df that I'm trying to clean. In instances where the value in col1 is = 0 I want to replace the 0 with the corresponding value from col2. What's the easiest way to do this?
edit: I got it nevermind..
Solution
One way is to use:
df['col1'] = df['col1'].replace(0, np.nan).fillna(df['col2'])
Another way with mask
:
df['col1'] = df['col1'].mask(df['col1'] == 0, other=df['col2'])
Or the opposite with where
:
df['col1'] = df['col1'].where(df['col1'] != 0, other=df['col2'])
And with loc
:
df.loc[df['col1'].eq(0), 'col1'] = df['col2']
Answered By - Corralien
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.