1

enter image description here

Here the nutrients column had 4 dictionaries in a list, each dictionary has 5 keys with 1 values on each key.

How can I flatten this nutrients column to make each as a sub column or row?

Actually it was a JSON file and I already flattened it into this. But I couldn't go further :(

Thanks for the help.

EDIT: Please see below for more information and what i tried:

enter image description here

enter image description here

enter image description here

enter image description here

3
  • 6
    can you post a sample of your JSON file in text form so we could copy, paste and develop a working solution? I guess it should be possible to flatten your JSON file in the way you want it without postprocessing Commented Apr 4, 2016 at 21:05
  • I posted a detailed comment below, if you want I can send another text form of the JSON file. Thanks again! Commented Apr 4, 2016 at 22:53
  • 1
    how do you think why did i mark "in text form" bold in my first comment? ;) Commented Apr 5, 2016 at 8:12

1 Answer 1

4

You can use json_normalize() in order to flatten your JSON file like this:

import ujson
import pandas as pd

with open('/path/to/your/file.json') as f:
    data = ujson.load(f)

df = pd.io.json.json_normalize(data, 'nutrients', ['measure','name','ndbno','weight'])

assuming that ['measure','name','ndbno','weight'] - aren't nested

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you @MaxU, but it doesn't work in my case. At least I couldn't.
@MaxU. And what if 'nutrients' is nested one more time. I am facing this same issue, but my 'nutrients' column has a second level and using (data, ['nutrients', 'something_else']) is not working.
@DanielVargas, please ask (open) a question and post there your data set (JSON) in text form and your desired data set
@MaxU i have actually done it several times. Please see one of them. stackoverflow.com/questions/47319424/digging-down-json-file
@MaxU I updated this question, and it is a lot more clear with a full chunck of the file. stackoverflow.com/questions/47242845/…
|

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.