How to convert a column that has fractions to decimals in python

Viewed 43

DataFrame example :

ID Rule Postion
1233 M-4/32 516.00
1235 M-8/32 716.00
1236 M-2/32 816.00

I need to split the Rule column which I tried to handle with:

DataFrame['effective date'] = DataFrame['Rule'].str.split(expand=True)

However this is not working the way I expected.

From there I need to convert the fraction portion of the rule column to a decimal and I cant figure out how.

If I can get the str.split function to work the way I need the conversion of the fraction should be straight forward.

Expected results:

ID Rule Postion Rule Final
1233 M-4/32 516.00 0.125
1235 M-8/32 716.00 0.25
1236 M-2/32 816.00 0.0625
2 Answers
df = pd.DataFrame({'ID': [1233], 'Rule': ['M-4/32'], 'Postion': [516.00]})
df['effective date'] = df['Rule'].str.split('-', expand=True)[1]
print(df)

Output:

     ID    Rule  Postion effective date
0  1233  M-4/32    516.0           4/32

If you want to go further and try to convert the string fraction into a float number:

df = pd.DataFrame({'ID': [1233], 'Rule': ['M-4/32'], 'Postion': [516.00]})
df['effective date'] = df['Rule'].str.split('-', expand=True)[1]
df.loc[df['effective date'].apply(lambda x: set(x) <= set('1234567890./')), 'effective date'] = df.loc[df['effective date'].apply(lambda x: set(x) <= set('1234567890./')), 'effective date'].apply(eval)
print(df)

The output:

     ID    Rule  Postion  effective date
0  1233  M-4/32    516.0           0.125

The condition .apply(lambda x: set(x) <= set('1234567890./')) was added, because otherwise the built-in function eval() is extremely dangerous.

decimal = []
for rule in DataFrame['Rule']:
    parts = rule.split("-")
    decimal_pts = parts[1].split("/")
    decimal.append(float(decimal_pts[0])/float(decimal_pts[1]))
DataFrame['effective date'] = decimal
Related