Cored
Cored

Reputation: 21

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:

dictionary

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.

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!

Upvotes: 2

Views: 65

Answers (1)

Guinther Kovalski
Guinther Kovalski

Reputation: 1909

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:

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

Upvotes: 2

Related Questions