subtracting two dataframes

喜欢而已 提交于 2019-12-28 23:42:22

问题


df1:

City, 2015-12-31, 2016-01-31, ...
YYZ  562.14, -701.18, ...
DFW  562.14, -701.18, ...
YYC  562.14, -701.18, ...

df2:

City, 2015-12-31, 2016-01-31, ...
SFO  562.14, -701.18, ...
PDX  562.14, -701.18, ...
LAX  562.14, -701.18, ...

I want to subtract df1 from df2. i.e. subtract values in respective date columns.

I tried the following:

df2.subtract(df1, fill_value=0)

But I receive the following error:

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

I think the error is because the operation cannot understand how to subtract strings in the City column, which obviously makes sense since subtracting the Cities is nonsensical.

The accepted answer in this post [link] seems to suggest this is possible. I am the author of that question but can't seem to get it to work now.


回答1:


Move the City column into the index. The DataFrames will align by both index and columns first and then do subtraction. Any combination not present will result in NaN.

df2.set_index('City').subtract(df1.set_index('City'), fill_value=0)



回答2:


Does this work?

df2.drop(['City']).subtract(df1.drop(['City']))


来源:https://stackoverflow.com/questions/40987908/subtracting-two-dataframes

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