简体   繁体   中英

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

在此处输入图像描述

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!

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

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]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM