减去两个数据帧 [英] 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, ...
我想从df2中减去df1.即减去各个日期列中的值.
I want to subtract df1 from df2. i.e. subtract values in respective date columns.
我尝试了以下操作:
df2.subtract(df1, fill_value=0)
但是我收到以下错误:
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.
这篇文章 [link] 中被接受的答案似乎暗示这是可能的.我是这个问题的作者,但现在似乎无法解决.
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.
推荐答案
将城市"列移到索引中. DataFrame将首先按索引和列对齐,然后进行减法.任何不存在的组合将导致NaN
.
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)
这篇关于减去两个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!