Reputation: 25
I tried creating a list from dataframe columns then create a dictionary from it. However, I couldn't produce a desired output because there are multiple keys(dataframe.index, dataframe.somecolumn).
I tried:
sample df:
index sender
0 Julia
0 Alfred
0 Nana
1 Kaja
1 Lunox
1 December
dict(zip(df.index, df.sender))
but it only retains the first value on the sender column.
desired output:
{0: [Julia, Alfred, Nana], 1: [Kaja, Lunox, December]}
Upvotes: 1
Views: 595
Reputation: 88275
As mentioned in the comments dictionaries cannot have duplicate keys
. One approach could be to groupby
the index
, aggregate with the list
constructor and use the .to_dict()
method:
df.groupby('index').sender.apply(list).to_dict()
# {0: ['Julia', 'Alfred', 'Nana'], 1: ['Kaja', 'Lunox', 'December']}
Upvotes: 1