Home > database >  groupby and convert rows into list using pandas
groupby and convert rows into list using pandas

Time:09-21

I have the below dataframe from which I need to groupby using id column and the corresponding values should be in list at the same cell. Anyone please help me on this?

I have this processed Dataframe:

enter image description here

Actual Dataframe:

enter image description here

In the actual dataframe, the list values should be added in the new column called e_values to the respective id.

CodePudding user response:

df['e_values'] = df.filter(like='col_').apply(list, axis=1)

CodePudding user response:

If going from Actual to processed; You can split, expand=True and then replace the corner brackets. This should give you a dataframe which you can rename columns

df['values'].str.split(',',expand=True).replace(regex={'\[': '', '\]': ''})

If going from processed to Actual use:

df.set_index('id').agg(list,1).reset_index()
  • Related