How to convert non-numbers in dataframe to NaN (numpy)?

for example, there is such a data frame:

   a     b
   --------
   10  ...
   4    5
   ...  6

how to hide it until:

   a    b
   --------
   10  NaN
   4   5
   NaN 6

Thanks in advance!

+4
source share
2 answers

IIUC you can just do

df = df.apply(lambda x: pd.to_numeric(x, errors='coerce') )

This will cause the duff values ​​to be NaN, note that the presence NaNwill change dtype to float, as NaNit cannot be representedint

In [6]:
df = df.apply(pd.to_numeric, errors='coerce')
df

Out[6]:
      a    b
0  10.0  NaN
1   4.0  5.0
2   NaN  6.0

lambda not required but this is a more readable IMO

+6
source

You can also stack, then unstackdataframe

pd.to_numeric(df.stack(), errors='coerce').unstack()

      a    b
0  10.0  NaN
1   4.0  5.0
2   NaN  6.0
+4
source

Source: https://habr.com/ru/post/1673324/


All Articles