2017-03-01 83 views
3

我有一个DataFrame df,从那里我想减去df2。减去两个不同大小的数据帧,但至少保持第一个数据帧的大小

需要注意的是,我希望df保持相同的大小,并且对于df中的每个元素,我想减去df2(如果df2中没有这种唯一索引/列),它只会是df(i,j) - 0(as在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 

谢谢。

回答

4

填写背面的差距:

(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 
2

Boud已经有你覆盖与一个伟大的答案,但捎带关闭它,你也可以只提供0填充值df.subtract,然后reindex_like

>>> df.subtract(df2, fill_value=0).reindex_like(df).astype(int) 
      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 

这看起来是从(粗糙)基准速度更快,因为我们能够避免combine_first组合。

%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
相关问题