从 pandas 数据框创建列表字典 [英] Creating a dictionary of lists from pandas data frame
本文介绍了从 pandas 数据框创建列表字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试基于pandas数据框创建列表字典,我需要为Plotly仪表板传递列表字典
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
我发现 df.to_dict( )
按列标题定位,但我需要根据相邻的行值进行定位。这样做的唯一方法是通过将Model的数据框重塑为具有其各自品牌的Model列吗?
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']
}
推荐答案
您可以 groupby
,汇总到列表中,返回 rec.array
与 to_records
并根据结果构建字典:
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']}
这篇关于从 pandas 数据框创建列表字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文