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

我的梦境 提交于 2021-02-19 05:42:54

问题


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??


回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/48339263/subtracting-two-columns-from-pandas-dataframe-and-store-the-result-in-third-colu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!