Search code examples
pythonpandasmathcalculationoperation

To calculate maths operation in a column using pandas


I would like to use python to get final values for maths operation in a column of a CSV file, may I know is it possible to get the value as below?

Original CSV:

Type Total
A    2+2
B    (10/2)*5
C    5-2*3

Expected Output:

Type Total
A    4
B    25
C    -1

I have tried searching around but I could not get any idea on it... All data are in string, I tried to convert to float but due to the maths operation, so it cannot be done.


Solution

  • Use pandas.eval with Series.apply:

    df['Total'] = df['Total'].apply(pd.eval)
    print (df)
    0    A    4.0
    1    B   25.0
    2    C   -1.0
    

    Dont use:

    df['Total'] = pd.eval(df['Total'])
    

    because failed if more like 100 rows.

    EDIT: If need working only for not missing values:

    mask = df['Total'].notna()
    df.loc[mask, 'Total'] = df.loc[mask, 'Total'].apply(pd.eval)
    

    EDIT1: If possible some values which cannot be processed use custom function with try-except:

    print (df)
      Type     Total
    0    A       2+2
    1    B  (10/2)*5
    2    C     5-2*3
    3    D       NaN
    4    E       aaa
    
    def func(x):
        try:
            return pd.eval(x)
        except:
            return x
    
    df['Total'] = df['Total'].apply(func)
    print (df)
      Type Total
    0    A     4
    1    B    25
    2    C    -1
    3    D   NaN
    4    E   aaa