Python 减去两个大小不同的数据帧,但至少保持第一个数据帧的大小
我有一个数据帧df,我想从中减去df2 需要注意的是,我希望df保持相同的大小,对于df中的每个元素,我希望减去df2(如果df2中没有这样唯一的索引/列),它将是Python 减去两个大小不同的数据帧,但至少保持第一个数据帧的大小,python,pandas,dataframe,subtraction,Python,Pandas,Dataframe,Subtraction,我有一个数据帧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
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
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
df2:
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
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
Boud已经为您提供了一个很好的答案,但是在它的基础上,您还可以提供一个0到然后的填充值 这看起来比(粗略的)基准测试更快,因为我们可以先避免
combine\u
组合
%timeit df.subtract(df2, fill_value=0).reindex_like(df).astype(int)
100 loops, best of 3: 3.63 ms per loop
%timeit (df-df2).combine_first(df).reindex_like(df).astype(int)
100 loops, best of 3: 8.69 ms per loop
%timeit df.subtract(df2,fill\u value=0).reindex\u like(df).astype(int)
100圈,最佳3圈:每圈3.63毫秒
%timeit(df-df2).先合并(df).像重新索引(df).aType(int)
100圈,最佳3圈:每圈8.69毫秒