0

This question got closed, but the mentioned question Keep other columns when doing groupby with the solution does not work for me.

I want to group by the child df on animals get the min birth_dates, apply this date to the colum date_of_birth to the the parent df where the animal is the index.

the child table :

Animals ... Brithdates
Frog ... 2021-02-10
Frog ... 2021-02-12
Tiger ... 2010-04-08
Tiger ... 2008-06-10
Fish ... 2005-12-10
Rabbit ... 2015-05-15

the parent table :

index ... date_of_brith
Frog ... 2021-02-10
Tiger ... 2008-06-10
Fish ... 2005-12-10
Rabbit ... 2015-05-15

At the moment I came up with the following steps: To get the min date_of_brith of each animal group. child_df.groupby('ANIMALS').brith_dates.min()

parent_df['date_of_birth']= parent_df['date_of_birth'].loc[child_df.groupby('ANIMALS').brith_dates.min()]

this gives me an error, how could I add the results to each specific index to the corresponding colum ?

1 Answers1

1

Use Index.map:

s = child_df.groupby('Animals').Brithdates.min()

parent_df['date_of_birth'] = parent_df.index.map(s)
print (parent_df)
        ... date_of_brith date_of_birth
index                                  
Frog    ...    2021-02-10    2021-02-10
Tiger   ...    2008-06-10    2008-06-10
Fish    ...    2005-12-10    2005-12-10
Rabbit  ...    2015-05-15    2015-05-15
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 1
    thank you it worked. i made it do a one line with: parent_df['date_of_birth'] = parent_df.index.map(child_df.groupby('ANIMALS').brith_dates.min()) – uncertainty Aug 12 '22 at 09:39