Search code examples
pythonpandasdataframesubtraction

subtracting two columns from pandas dataframe and store the result in third column


I have a DataFrame, df, with 3 columns and I want to perform subtraction as follows:

df['available'] = df['recommended'] - df['manual input']

But I am getting an error stating:

unsupported operand type(s) for -: 'int' and 'str'

I have also tried doing

df['available'] = df['recommended'].sub(df['manual input'])

but it shows the same error.

Also I would like to know that does it returns Series if we try to get particular column from dataframe??


Solution

  • You have to convert values to numeric - e.g. to integers:

    df['available'] = df['recommended'] - df['manual input'].astype(int)
    

    Or to floats:

    df['available'] = df['recommended'] - df['manual input'].astype(float)