Reputation: 33
import pandas as pd
df = pd.DataFrame({'Name': ['John', 'John', 'Sara', 'Sara', 'Sara', 'Peter', 'Peter'],
'Age': [11, 22, 33, 44, 55, 66, 77]})
Assume that I have a data frame which is given above. My goal is to convert this data frame to the following dictionary format below. Does anybody know a convenient way to solve this problem? Thanks in advance.
# Expected Output:
out_df = {'John':[11, 22], 'Sara': [33, 44, 55], 'Peter': [66, 77]}
Upvotes: 0
Views: 43
Reputation: 862661
First aggregate list and then convert Series
to dictionary:
d = df.groupby('Name')['Age'].agg(list).to_dict()
Upvotes: 2