Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify dataframe in place using nan values from passed dataframe

Tags:

python

pandas

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
like image 549
INGl0R1AM0R1 Avatar asked Oct 23 '25 17:10

INGl0R1AM0R1


1 Answers

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
like image 129
BeRT2me Avatar answered Oct 26 '25 07:10

BeRT2me