Grouping a Python Dataframe containing columns with column locations

Viewed 29

I have this dataframe below where i am trying to group each them into a single row by person and purchase id. column purchase date location contains the column name in which the date is located for said purchase. i am trying to use the location to determine the earliest date a purchase was made

person purchase_id purchase_date_location column_z column_x final_pruchase_date
a 1 column_z NaN NaN
a 1 column_z 2022-01-01 NaN
a 1 column_z 2022-02-01 NaN
b 2 column_x NaN NaN
b 2 column_x NaN 2022-03-03

i have tried this so far:

groupings = {df.purchase_date_location.iloc[0]: 'min'}

df2 = df.groupby('purchase_id', as_index=False).agg(groupings)

My problem here is due to the iloc[0] my value will always be column_z, my question is how do i make this value change corresponding to the row and not be fixated on the first

1 Answers

I would try solve it like this:

df['purchase_date'] = df[['purchase_date_location']].apply(
                           lambda x: df.loc[x.name, x.iloc[0]], axis=1)
df2 = df.groupby('purchase_id', as_index=False).agg({"purchase_date": min})
Related