Pat
Pat

Reputation: 41

Creating a dictionary of lists from pandas data frame

I'm trying to create a dictionary of lists based on a pandas dataframe, I need a dictionary of lists to pass for my Plotly dashboard

In:
df.head()
Model    Make
Ford     F-150
Ford     Escape
Ford     Mustang
Jeep     Grand Cherokee
Jeep     Wrangler

I found df.to_dict() orients by column header but I need to orient based on neighboring row value. Is the only way to do this by re-shaping my dataframe into columns by Model with their respective makes under them?

Out:
makes_by_model= {
    'Ford': ['F-150', 'Escape', 'Mustang'],
    'Jeep': ['Wrangler', 'Grand Cherokee']
}

Upvotes: 1

Views: 84

Answers (1)

yatu
yatu

Reputation: 88305

You can groupby, aggregate to lists, return a rec.array with to_records and construct a dictionary from the result:

dict(df.groupby('Model').agg(list).to_records())
# {'Ford': ['F-150', 'Escape', 'Mustang'], 'Jeep': ['Grand Cherokee', 'Wrangler']}

Upvotes: 6

Related Questions