-1

I need to convert numeric values of a column (pandas data frame) to float, but they are in string format.

d = {'col1': ['1', '2.1', '3.1'], 
     'col2': ['yes', '4', '6'],
     'col3': ['1', '4', 'not']}

Expected:

{'col1': [1, 2.1, 3.1],
 'col2': ['yes', 4, 6],
 'col3': [1, 4, 'not']}
stefanodv
  • 463
  • 3
  • 11
  • 20
  • Possible duplicate of [Converting strings to floats in a DataFrame](https://stackoverflow.com/questions/16729483/converting-strings-to-floats-in-a-dataframe) – vahdet Feb 18 '19 at 13:51

1 Answers1

3

It is possible, but not recommended, because if mixed values in columns some function should failed:

d = {'col1': ['1', '2.1', '3.1'], 
     'col2': ['yes', '4', '6'],
     'col3': ['1', '4', 'not']}
df = pd.DataFrame(d)


def func(x):
    try:
        return float(x)
    except Exception:
        return x

df = df.applymap(func)
print (df)
   col1 col2 col3
0   1.0  yes    1
1   2.1    4    4
2   3.1    6  not

print (df.to_dict('l'))
{'col1': [1.0, 2.1, 3.1], 'col2': ['yes', 4.0, 6.0], 'col3': [1.0, 4.0, 'not']}

Another solution:

df = df.apply(lambda x: pd.to_numeric(x, errors='coerce')).fillna(df)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252