Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid NaNs in applymap()?

Tags:

python

pandas

I'm trying to do a simple operation, converting a dataframe to titlecase.

There are some NaNs which cause errors, so I'd like to avoid them by applying str.title() only if it's not null.

However I'm getting invalid syntax.

df= df.applymap(lambda x: x.title() if pd.notnull(x))
                                                                    ^
SyntaxError: invalid syntax

Another try:

df= df.applymap(lambda x: x.title() if not pd.isnull(x))

SyntaxError: invalid syntax
like image 350
SCool Avatar asked Jun 13 '26 09:06

SCool


2 Answers

this is a conditional expression you have to also provide a value for the else (if the condition is not met).

try this:

df= df.applymap(lambda x: x.title() if pd.notnull(x) else '')
like image 181
Adam.Er8 Avatar answered Jun 15 '26 02:06

Adam.Er8


pandas.Series.str.title

df.stack().str.title().unstack()

numpy.core.defchararray.title

from numpy.core.defchararray import title

title(df.to_numpy().astype(str))
like image 27
piRSquared Avatar answered Jun 15 '26 02:06

piRSquared