Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use applymap, lambda and dataframe together to filter / modify dataframe in python?

So I 'm trying to figure it out how to replace NaN in pd.DataFrame .. ? Here in the example I created the 3x3 dataframe, having value in df[1][2] = 'a' and the rest are NaN

My understanding is that I can use if with in lambda and do something below. But the result was not what I expected, it overwrite 'a'. I still want 'a' to remain as it is and only change to 'o' where is NaN ... Any recommendation would be appreciated.

enter image description here

df = pd.DataFrame(index=range(0,3),columns=range(0,3))
df[1][2] = 'a'
f = lambda x: 'o' if np.nan else x
df.applymap(f)
like image 713
JPC Avatar asked Jan 06 '23 18:01

JPC


1 Answers

Instead of using apply, you could use fillna.

df.fillna('o')

For more information about Working with missing data. You could also use apply with pd.isnull() as mentaioned in @Psidom answer. But in this case, you should really use the built-in function fillna.

like image 119
MaThMaX Avatar answered Jan 09 '23 18:01

MaThMaX