2

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!

4
  • 1
    Can you please provide more accurate example? DataFrame and Dictionary data does not match. I mean: this dataframe with this values I want to transform to dict with this structure. According to this data solution can be: result = comments_df["comments"].to_dict(orient="records"). But without further more info i cannot help. Commented Sep 27, 2021 at 16:09
  • Please don't post pictures of text. Instead, copy the text, edit it into your post, and use the formatting tools like code formatting. (Links formatted as code don't count as links, which is probably what was stopping you before.) Commented Sep 27, 2021 at 16:23
  • 1
    I assume you're using Pandas, so I added the pandas tag for you. If that's incorrect, you can edit to fix it. Pandas has a bunch of idioms that aren't part of standard Python, so it's important to tag it. Commented Sep 27, 2021 at 16:31
  • BTW, welcome to Stack Overflow! Check out the tour, and How to Ask if you want tips. Commented Sep 27, 2021 at 16:37

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.