import pandas as pd
df = pd.read_csv("dataset.csv")
trying to change an object type to float
df['Charge'] = (df['Charge']).astype('float')
ValueError: could not convert string to float: '(94.00)'
There are no commas or special characters in data just . and i need to keep decimal point
however it will allow me to change to string but I need it as a float because i get errors when try to work on a string
CodePudding user response:
ValueError: could not convert string to float: '(94.00)'
So you have this str
ing: '(94.00)'
. Do you know what (94.00)
is? A tuple
containing a single float
, and not a float
.
So, if you want to get the 94.00
from inside the tuple, you have to cast to float only the part of the string without ()
.
CodePudding user response:
you cant convert a (94.00) to float but you can do it to 94.00 So you can use a delimiter
this may help you
CodePudding user response:
Sometimes I have the same issue too. The problem here is the parenthesis: ()
So I first remove them with regex:
df['Charge'].str.replace('\(','',regex=True).str.replace('\)','',regex=True)
Then I apply.astype(float)
Here my TestDf:
df_test=pd.DataFrame(['(201536.34)','(133104.47)', '66579.82', '95129.99',
'72333.23', '61319.77', '60705.00', '47944.47', '35510.36', ('28530.77')])
df_test[0]
Out[47]:
0 (201536.34)
1 (133104.47)
2 66579.82
3 95129.99
4 72333.23
5 61319.77
6 60705.00
7 47944.47
8 35510.36
9 28530.77
Name: 0, dtype: object
When trying to convert it to float I get the same error as you: ValueError: could not convert string to float: '(201536.34)'
df_test[0]=df_test[0].str.replace('\(','',regex=True).str.replace('\)','',regex=True)
df_test[0]
Out[72]:
0 201536.34
1 133104.47
2 66579.82
3 95129.99
4 72333.23
5 61319.77
6 60705.00
7 47944.47
8 35510.36
9 28530.77
Name: 0, dtype: object
Now ready to use astype('float)
df_test[0].astype('float')
Out[74]:
0 201536.34
1 133104.47
2 66579.82
3 95129.99
4 72333.23
5 61319.77
6 60705.00
7 47944.47
8 35510.36
9 28530.77
Name: 0, dtype: float64