简体   繁体   English

从 pandas 数据帧创建列表字典

[英]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我正在尝试基于 pandas dataframe 创建一个列表字典,我需要一个列表字典来传递给我的 Plotly 仪表板

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.我发现df.to_dict()按 header 列定向,但我需要根据相邻行值定向。 Is the only way to do this by re-shaping my dataframe into columns by Model with their respective makes under them?唯一的方法是通过 Model 将我的 dataframe 重新塑造成列,并在它们各自的品牌之下?

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:您可以groupby ,聚合到列表,返回一个带有rec.arrayto_records并从结果中构造一个字典:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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