How to add a multidimensional dataframe to another multidimensional dataframe as a union?

Viewed 32

I have the following dataframes:

The MAIN dataframe A:

   A  B
0  1  0
1  1  0

The second dataframe B:

   A  B
0  0  1
1  1  0

The third dataframe C:

   A  B  C
0  1  0  0
1  0  1  1
2  0  0  1

In python pandas, I want to add A,B and Cthem in such a way that the structure of the resulting dataframe D consists of same columns and rows structure as the MAIN dataframe A while the the values of rows/columns are added.

A + B + C

   A  B 
0  2  1 
1  2  1 

And by Union addition, I mean that if values > 1, make it 1. So the final A + B + C is:

   A  B 
0  1  1 
1  1  1 

As you can see, the structure of first A dataframe is maintained while the values from common rows and columns are added. The common rows and columns are variable so I need a code to do this automatically by detecting common rows and columns. Any ideas how to do this?

UPDATE

Please note that the data frames can multidimensional: For example:

A

      A  B 
0  a  2  1 
1  a  2  1 

C

      A  B  C
0  a  1  0  0
0  b  1  0  0
0  b  1  0  0
1  a  0  1  1
2  c  0  0  1

In this case I am expecting: A + C to be:

      A  B 
0  a  3  1 
1  a  2  2

Thereby keeping the structure of MAIN dataframe A. Then 'binarized' to

      A  B 
0  a  1  1 
1  a  1  1
3 Answers

IIUC:

In [56]: (d1 + d2 + d3).dropna(how='all').dropna(axis=1, how='all').ne(0).astype(np.int8)
Out[56]:
   A  B
0  1  1
1  1  1

UPDATE:

In [129]: idx = A.index.intersection(C.index)

In [131]: (A.loc[idx] | B.loc[idx, A.columns]).gt(0).astype('int8')
Out[131]:
     A  B
0 a  1  1
1 a  1  1
((dfA+dfB+dfC).reindex(index=dfA.index,columns=dfA.columns)>=1).astype(int)
Out[252]: 
   A  B
0  1  1
1  1  1

Updated :

(A+C).reindex(A.index,columns=A.columns)
Out[297]: 
       A    B
0 a  3.0  1.0
1 a  2.0  2.0

Depending a bit on how much of your given structure will generalize,

In [50]: df_a | df_b | df_c.loc[df_a.index, df_a.columns]
Out[50]:
   A  B
0  1  1
1  1  1
Related