简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM