Bijan
Bijan

Reputation: 8586

Add values from Pandas row to dictionary

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()?

Upvotes: 3

Views: 285

Answers (1)

Michael Szczesny
Michael Szczesny

Reputation: 5036

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

Upvotes: 2

Related Questions