Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtracting two dataframes

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.

like image 601
codingknob Avatar asked Dec 06 '16 04:12

codingknob


People also ask

Can you subtract 2 DataFrames?

subtract() function is used for finding the subtraction of dataframe and other, element-wise. This function is essentially same as doing dataframe – other but with a support to substitute for missing data in one of the inputs.

How do you subtract two sets of data?

Accepted Answer In order to subtract two data sets with different resolutions, it is required to convert the resolution of one of the data sets to match that of the other one. Use MATLAB function GRIDDATA for this purpose. ZZ3 = griddata(XX,YY,ZZ,XX2,YY2);

How do you subtract values in pandas?

Pandas DataFrame sub() MethodThe sub() method subtracts each value in the DataFrame with a specified value. The specified value must be an object that can be subtracted from the values in the DataFrame.


1 Answers

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)
like image 97
Ted Petrou Avatar answered Oct 11 '22 10:10

Ted Petrou