我有一个 DataFrame df,我想从那里减去 df2。
需要注意的是,我希望 df 保持相同的大小,对于 df 中的每个元素,我想减去 df2(如果 df2 中没有这样的唯一索引/列),它只是 df (i,j) - 0
(因为在 df2 中找不到这样的索引/列)。
例子:
df:
Date Blue Dog Apple
1/1/2016 3 4 2
1/1/2015 3 4 2
1/1/2014 3 4 2
1/1/2013 3 4 2
1/1/2013 3 4 2
1/1/2013 3 4 2
df2:
Date Apple Blue Cat
1/1/2017 1 3 2
1/1/2016 1 3 2
1/1/2015 1 3 2
1/1/2014 1 3 2
我希望 df - df2 看起来像这样:
Date Blue Dog Apple
1/1/2016 0 4 1
1/1/2015 0 4 1
1/1/2014 0 4 1
1/1/2013 3 4 2
1/1/2012 3 4 2
1/1/2011 3 4 2
谢谢。
最佳答案
填补空白:
(df-df2).combine_first(df).reindex_like(df).astype(int)
Out[45]:
Blue Dog Apple
Date
1/1/2016 0 4 1
1/1/2015 0 4 1
1/1/2014 0 4 1
1/1/2013 3 4 2
1/1/2012 3 4 2
1/1/2011 3 4 2
关于python - 减去两个不同大小的数据帧,但至少保持第一个数据帧的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42542026/