2017-03-01 4 views
3

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 

감사합니다.

답변

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은 이미 훌륭한 대답으로 덮여 있지만, 떨어져 편승하고있다, 당신은 단지 df.subtract 다음 reindex_like 0의 채우기 값을 제공 할 수있다. 그것이 빨리 (거친) 벤치 마크에서처럼

>>> 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
관련 문제