I'm making using a panda frame containing columns like below:
data = {'chindice': [ '-1', '5.89 e-06', '6.76 e-06', '6.31 e-06', '1',
'4', np.nan],
'target': ['classe1', 'classe2', 'classe3', np.nan,'classe5', 'classe4', 'classe5' ],
}
df = pd.DataFrame(data)
I need to use the columns "chindice" as float, but I couldnt because the columns dtype is 'object'. Any help would be appreciated. I am a newbie to pandas. Thanks
pandas Convert String to Float Use pandas DataFrame. astype() function to convert column from string/int to float, you can apply this on a specific column or on an entire DataFrame. To cast the data type to 54-bit signed float, you can use numpy. float64 , numpy.
We will convert this object to float using pd. to_numeric() and astype() functions in Pandas.
Using astype() astype() method is used to cast a pandas column to the specified dtype.
You can use to_numeric
after stripping the problematic space in your scientific notation entries using str.replace
:
In [15]:
df['chindice'] = pd.to_numeric(df['chindice'].str.replace(' ',''), errors='force')
df
Out[15]:
chindice target
0 -1.000000 classe1
1 0.000006 classe2
2 0.000007 classe3
3 0.000006 NaN
4 1.000000 classe5
5 4.000000 classe4
6 NaN classe5
Don't worry about the display, the real value is still there:
In [17]:
df['chindice'].iloc[1]
Out[17]:
5.8900000000000004e-06
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With