2

I have a dataframe that has several columns like [name, email, country, city, type, time, x_completions] as follows:

I want to convert each row of this dataframe to a JSON object but group some columns into a dict and call it user_info like { "name": "XYZ", "email": "[email protected]", "country": "USA", "city": "NYC"}

Basically, I want to convert each row into a JSON object of the following structure:

{ "type":"Login", "user_id":"002203293023", "user_info":{ "name":"XYZ", "email":"[email protected]", "country":"USA", "city":"NYC" }, "other_info":{ "x_completed":"4" }, "time":1562932893 }

I'm not sure how to go about converting groups of columns to dicts within JSON objects. All the other similar questions on SO deal with some form of groupby operation which I don't think I need here.

1 Answer 1

4

Use a list comprehension to iterate through each row in your dataframe.

[{
   "type": "Login",
   "user_id": row['user_id'],
   "user_info":{
      "name": row['name'],
      "email": row['email'],
      "country": row['country'],
      "city": row['city']
   },
   "other_info":{
      "x_completed": row['x_completions']
   },
   "time": row['time']
} for _, row in df.iterrows()]
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.