Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I clean this data type object and transform it to type float maintaining Null and NaN

Tags:

python

pandas

I have the following dataframe column:

                           Hight
0                       
1               1,82 m (6 ft 0 in)
2        1,74 m (5 ft 9 in) metres
3               1,88 m (6 ft 2 in)
4                              NaN
5       1,80 m (5 ft 11 in) metres

How can I transform the column Hight to data type float and keep the NaN values?

Desired output:

Hight
0                              NaN
1                             1.82 
2                             1.74
3                             1.88
4                              NaN
5                             1.80

thanks a lot in advance

like image 230
ruben.lfdz Avatar asked Jan 14 '20 00:01

ruben.lfdz


1 Answers

Try:

pd.to_numeric(df.Hight.str.extract('([\d,]+) m')[0].str.replace(',','.'))

Output:

0     NaN
1    1.82
2    1.74
3    1.88
4     NaN
5    1.80
Name: 0, dtype: float64
like image 94
Quang Hoang Avatar answered Oct 08 '22 21:10

Quang Hoang