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.