Skip to content
Advertisement

Pandas Dataframe loop to append values to a list for each unique name

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!

Advertisement

Answer

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]}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement