loadbox
loadbox

Reputation: 656

Converting pandas dataframe to dictionary

While converting the pandas dataframe to dictionary, how can I append all the different values to the list ? Reference: Convert a Pandas DataFrame to a dictionary

The answers for this question specifies the solution but it gives me the following output:

df = pd.DataFrame({'a': ['red', 'yellow', 'blue', 'red'], 'b': [0.5, 0.25, 0.125, 0.9]})
>>> df.set_index('a').T.to_dict('list')
{'red': [0.9], 'yellow': [0.25], 'blue': [0.125]}

Expected output:

{'red': [0.5,0.9], 'yellow': [0.25], 'blue': [0.125]}

Upvotes: 1

Views: 103

Answers (1)

jezrael
jezrael

Reputation: 862471

Use DataFrame.groupby with lists and Series.to_dict:

print (df.groupby('a')['b'].apply(list).to_dict())
{'blue': [0.125], 'red': [0.5, 0.9], 'yellow': [0.25]}

Upvotes: 2

Related Questions