-1
$\begingroup$

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'
$\endgroup$
2
$\begingroup$

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[0]) / float(x[1]))

#      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
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.