词典列表列表
我有以下df:
df = pd.DataFrame({"year":[2020,2020,2020,2021,2021,2021,2022,2022, 2022],"region":['europe','USA','africa','europe','USA','africa','europe','USA','africa'],'volume':[1,6,5,3,8,7,6,3,5]})
我希望将其转换为字典列表,以便每项仅在每个项目中提及一次。例如
[{'year':2020,'europe':1,'USA':6,'africa':5,}...]
:
df.set_index('year').to_dict('records')
我丢失了岁月和清单
I have the following df:
df = pd.DataFrame({"year":[2020,2020,2020,2021,2021,2021,2022,2022, 2022],"region":['europe','USA','africa','europe','USA','africa','europe','USA','africa'],'volume':[1,6,5,3,8,7,6,3,5]})
I wish to convert it to a list of dictionary such that the year would be mentioned only once in each item. Example
[{'year':2020,'europe':1,'USA':6,'africa':5,}...]
when I do:
df.set_index('year').to_dict('records')
I lost the years and the list
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在
to_dict(orient ='records')之前使用枢轴的另一种方法
Another approach that uses pivot before
to_dict(orient='records')
尝试:
打印:
Try:
Prints:
您可以一年使用Groupby,然后可以使用邮政区和音量
you can use groupby on year and then zip region and volume
要分解每个步骤,您可以使用Pivot将DF分组以汇总几年,您的列成为国家,并且数量成为您的价值观,
将其变成字典格式,您可以使用.to_dict('index')
命令(一行)
最后您可以使用列表理解将其纳入所需格式
To break down each step, you could use pivot to group your df to aggregate the years, your columns become countries, and volume becomes your values
To get this into dictionary format you can use the .to_dict('index')
command (in one line)
finally you could use list comprehension to get it into your desired format