# How can I convert a dataframe column of fraction float that is stored as a string into float? [closed]

The df is as follows:

>>> df['csl']
0       250/500
1      500/1000
2      500/1000
3      500/1000
4       100/300
695    500/1000
696     250/500
697     100/300
698     250/500
699     250/500
Name: csl, Length: 700, dtype: object


by the dtype is in the form of array objects:

df.unique()
array(['250/500', '500/1000', '100/300'], dtype=object)


The following code gives me an error:

df['csl'] = df['csl'].astype(float)
ValueError: could not convert string to float: '250/500'


The easiest way of achieving this would probably to split the string column using the fraction character and then dividing the first value by the second value:

import pandas as pd

df = pd.DataFrame({"col": ["250/500", "100/300", "500/1000"]})
df["result"] = df["col"].str.split("/").apply(lambda x: float(x) / float(x))

#      col    result
#  250/500  0.500000
#  100/300  0.333333
# 500/1000  0.500000


If you have a very large dataframe it is faster to save the intermediate result and then perform the division to make use of vectorization:

df[["numerator", "denominator"]] = df["col"].str.split("/", expand=True)
df["result"] = df["numerator"].astype(float) / df["denominator"].astype(float)

#      col numerator denominator    result
#  250/500       250         500  0.500000
#  100/300       100         300  0.333333
# 500/1000       500        1000  0.500000