Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to join 2 Dataframes, and store certain data as an array in one cell

Tags:

python

pandas

I have the following 3 data frames:

Frist dataframe:

DF1: 

iID data1 data2

10  blue  green

11  red   teal

Second dataframe:

DF2:

iID rH repH

10  50 60 

10  60 70 

11  70 50 

(DF2 to can have either 1 or 2 rows per iID)

I want my output DF to have an array in one cell for rH and repH

do output would be something like:

OUTPUT DF:

iID data1 data2 rH      repH

10  blue  green [50,60] [60,70]

11  red   teal  [70]    [50]
like image 288
JS noob Avatar asked Mar 26 '26 10:03

JS noob


1 Answers

IIUC

df1.merge(df2.groupby('iID').agg(lambda x : x.tolist()).reset_index())
Out[144]: 
   iID data1  data2        rH      repH
0   10  blue  green  [50, 60]  [60, 70]
1   11   red   teal      [70]      [50]
like image 63
BENY Avatar answered Mar 29 '26 01:03

BENY



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!