Convert Pandas integer data containing NaN values ​​from string to float

I would like to convert all values ​​to a pandas framework from strings to float. My data frame contains various NaN values ​​(e.g. NaN, NA, None). For instance,

import pandas as pd
import numpy as np

my_data = np.array([[0.5, 0.2, 0.1], ["NA", 0.45, 0.2], [0.9, 0.02, "N/A"]])
df = pd.DataFrame(my_data, dtype=str)

I have found here and here (among other places) that convert_objects can be a way, however, I get a message stating that it is deprecated (I use pandas 0.17.1) and should use to_numeric instead.

df2 = df.convert_objects(convert_numeric=True)

Output:

FutureWarning: convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

But to_numeric doesn't seem to actually convert strings.

df3 = pd.to_numeric(df, errors='force')

Output:

df2:
     0     1    2
0  0.5  0.20  0.1
1  NaN  0.45  0.2
2  0.9  0.02  NaN

df2 dtypes:
0    float64
1    float64
2    float64
dtype: object

df3:
     0     1    2
0  0.5   0.2  0.1
1   NA  0.45  0.2
2  0.9  0.02  N/A

df3 dtypes:
0    object
1    object
2    object
dtype: object

Should I use convert_objects and deal with a warning message, or is there a way to do what I want with to_numeric?

+4
2

:

In [11]:
df.apply(lambda x: pd.to_numeric(x, errors='force'))

Out[11]:
     0     1    2
0  0.5  0.20  0.1
1  NaN  0.45  0.2
2  0.9  0.02  NaN

, df - , .

( @Zero), :

df.apply(pd.to_numeric, errors='force')
+1

replace astype:

import pandas as pd
import numpy as np

my_data = np.array([[0.5, 0.2, 0.1], ["NA", 0.45, 0.2], [0.9, 0.02, "N/A"]])
df = pd.DataFrame(my_data, dtype=str)

print df.replace({r'N': np.nan}, regex=True).astype(float)
     0     1    2
0  0.5  0.20  0.1
1  NaN  0.45  0.2
2  0.9  0.02  NaN
+1

All Articles