Home > Mobile >  Pandas, convert values of DataFrames into tuple-DataFrame
Pandas, convert values of DataFrames into tuple-DataFrame

Time:02-26

I have a DataFrame:

      0  1  2
   0  1  4  7
   1  2  5  8
   2  3  6  9

and a second DataFrame:

        0   1   2
    0  10  13  16
    1  11  14  17
    2  12  15  18

and i need this two Dataframes to become this one DataFrame:

         0        1        2
     0  (1, 10)  (4, 13)  (7, 16)
     1  (2, 11)  (5, 14)  (8, 17)
     2  (3, 12)  (6, 15)  (9, 18)

I need nice little tuples, all together in one frame. How is that possible?

CodePudding user response:

Create tuples in both DataFrames and join by :

df = df1.applymap(lambda x: (x, ))   df2.applymap(lambda x: (x, ))
print (df)
         0        1        2
0  (1, 10)  (4, 13)  (7, 16)
1  (2, 11)  (5, 14)  (8, 17)
2  (3, 12)  (6, 15)  (9, 18)

Or join by concat and aggregate by index tuple:

df = pd.concat([df1, df2]).groupby(level=0).agg(tuple)
print (df)
         0        1        2
0  (1, 10)  (4, 13)  (7, 16)
1  (2, 11)  (5, 14)  (8, 17)
2  (3, 12)  (6, 15)  (9, 18)
  • Related