简体   繁体   English

使用 python 将 Dataframe 转换为字典

[英]Converting Dataframe into dictionary using python

I have a dataframe like this:我有一个这样的 dataframe:

数据框

and i want to convert it into a dictionary using exactly this format:我想使用这种格式将它转换成字典:

字典

Do you guys have an idea on how to do that?你们知道如何做到这一点吗?

I also tried using df.T.to_dict() but it gives me some problems with the indices as well as a starting and end clip.我也尝试过使用df.T.to_dict()但它给我带来了一些关于索引以及开始和结束剪辑的问题。

I figured it is some nesting problem, but I don't know how get rid of it:/我认为这是一些嵌套问题,但我不知道如何摆脱它:/

Please don't mind the harsh comments:) It is for a hate speech detection project!请不要介意苛刻的评论:)这是一个仇恨言论检测项目!

Also I'm a new user so I don't have the reputation to post snippets directly!另外我是新用户,所以我没有直接发布代码片段的名誉! Sry for that!对不起!

you can do something like this:你可以这样做:

[{"comments":comments} for comments in dataframe.comments]

you can also use .apply which is multiple (even thousands) times faster than iterate item by item in the dataframe:您还可以使用.apply ,它比 dataframe 中逐项迭代快数倍(甚至数千倍):

df.apply(lambda row: {"comments":row.comments}, axis=1).tolist()

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

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