Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join Two Pivot Table and obtain multi value per cell in panda

I have two pivot table with the same rows and columns, and I need create one table with the value separeted by comas in the cell with equal row and col.

For example

Table 1

       1    2    3    4
a     t1a1 t1a2 t1a3 t1a4
b     t1b1 t1b2 t1b3 t1b4

Table 2

       1    2    3    4
a     t2a1 t2a2 t2a3 t2a4
b     t2b1 t2b2 t2b3 t2b4

I want:

Table result

          1             2           3            4
a     (t1a1,t2a1)   (t1a2,t2a2)  (t1a3,t2a3)   (t1a4,t2a4)
b     (t1b1,t2b1)   (t1b2,t2b2)   (t1b3,t2b3)   (t1b4,t2b4)

The concat function return

        1    2    3    4   1    2    3    4
a     t1a1 t1a2 t1a3 t1a4  t2a1 t2a2 t2a3 t2a4
b     t1b1 t1b2 t1b3 t1b4  t2b1 t2b2 t2b3 t2b4  

I work in python with pandas library

Thanks

like image 720
Dafne Avatar asked Dec 03 '25 13:12

Dafne


1 Answers

You can use concanecation all DataFrames if need strings output:

df = '(' + df1 + ' , ' + df2 + ')'
#if numeric columns first cast to str
#df = '(' + df1.astype(str) + ' , ' + df2.astype(str) + ')'
print (df)
               1              2              3              4
a  (t1a1 , t2a1)  (t1a2 , t2a2)  (t1a3 , t2a3)  (t1a4 , t2a4)
b  (t1b1 , t2b1)  (t1b2 , t2b2)  (t1b3 , t2b3)  (t1b4 , t2b4)

If need tuples:

df = pd.concat([df1, df2],  keys=['a','b']) \
       .groupby(level=1).agg(lambda x: tuple(x))
print (df)
              1             2             3             4
a  (t1a1, t2a1)  (t1a2, t2a2)  (t1a3, t2a3)  (t1a4, t2a4)
b  (t1b1, t2b1)  (t1b2, t2b2)  (t1b3, t2b3)  (t1b4, t2b4)
like image 111
jezrael Avatar answered Dec 06 '25 04:12

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!