Search code examples
pythonpandasdata-sciencedata-cleaningfeature-selection

How to Handle a Column of string of integers to apply a mathematical operation on it


enter image description here

I have a Column with data as a String. I want to replace all these values with their actual ratios i.e '6.2/5.1' to 1.2156 i.e their actual value after division as I cannot use the original values directly in my model. I tried splitting the strings using the strip function but I don't understand how to replace it with values at the correct place.


Solution

  • I am not sure but i think you can use eval and apply to get the job done.

    df['DELTA-T(L/R)'].apply(eval)
    

    UPDATE: I tried and it works.. Here is the sample:

    df = pd.DataFrame({'ratio': ['1.2/.25', '1/2',  '2/3']})
    df
         ratio
    0  1.2/.25
    1      1/2
    2      2/3
    df['ratio'].apply(eval)
    0    4.800000
    1    0.500000
    2    0.666667
    Name: ratio, dtype: float64