Add values from Pandas row to dictionary

Viewed 107

I have a dataframe in Pandas that has columns that will correspond to the key and value of a dict.

for values in ['A','B']:
    MYDICT[values] = [] # Initialize to empty list

Name    ID    othercolumns
A       5     ...
B       6     ...
A       3     ...

I am trying to find a simple way to assign every value of Name to ID so MYDICT[NAME].append(ID)

The solution I currently have is to iterate over every row in the dataframe

for index, x in df.iterrows():
    WINNERS[x['Name']].append(x['ID'])

Is there a better way to do this without having to use iterrows()?

1 Answers

You can group by Name and aggregate ID into a list

WINNERS = df.groupby('Name')['ID'].apply(list).to_dict()
WINNERS

Out:

{'A': [5, 3], 'B': [6]}
Related