So i have the following sample df
df = pd.DataFrame({'Id':[1,1,2,3],'Origin':['int','int','pot','pot'],'Origin2':['pot','int','int','int']})
Id Origin Origin2
0 1 int pot
1 1 int int
2 2 pot int
3 3 pot int
And i do the following replace command
df.loc[df['Id'].eq(1)].apply(lambda x : x.replace('int':np.nan))
How could i update the original df, with both new columns using indexes.
I tried df.update but after checking the documentation, i noticed it doesnt substitute 'non na' values by nan values?
For better understanding, the columns in the index [0,1] ('id'= 1). Substitute the string 'int' by np.nan
Wanted result:
df = pd.DataFrame({'Id':[1,1,2,3],'Origin':[np.nan,np.nan,'pot','pot'],'Origin2':['pot',np.nan,'int','int']})
Id Origin Origin2
0 1 NaN pot
1 1 NaN NaN
2 2 pot int
3 3 pot int
mask = df.Id.eq(1)
cols = ['Origin','Origin2']
df.loc[mask, cols] = df.replace('int', np.nan)
Output:
Id Origin Origin2
0 1 NaN pot
1 1 NaN NaN
2 2 pot int
3 3 pot int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With