Home > Software engineering >  Pandas Dataframe loop to append values to a list for each unique name
Pandas Dataframe loop to append values to a list for each unique name

Time:02-28

I have the following dataframe:

import pandas as pd
#Create DF

           
df = pd.DataFrame({ 
     'Name': ['Jim','Jack','Jim','Jack','Jim','Jack','Mick','Mick'],
    'Day':[1,1,2,2,3,3,4,4],
    'Value':[10,20,30,40,50,60,70,80],
    })
df

enter image description here

I would like to create a list for each unique Name and append the Value values to each list.

My expected output is:

Jim = [10,30,50]
Jack = [20,40,60]
Mick = [70,80]

Any ideas on the most efficient way to do this? thank you!

CodePudding user response:

To aggregate as dictionary, you can use:

df.groupby('Name')['Value'].agg(list).to_dict()

Output:

{'Jack': [20, 40, 60],
 'Jim': [10, 30, 50],
 'Mick': [70, 80]}

CodePudding user response:

You could do:

result = df.groupby('Name').Value.agg(list)

Result:

Name
Jack    [20, 40, 60]
Jim     [10, 30, 50]
Mick        [70, 80]
Name: Value, dtype: object
  • Related