lorelai
lorelai

Reputation: 83

Nested List of Dictionaries in Pandas DataFrame

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

Upvotes: 1

Views: 8309

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

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

Upvotes: 4

Related Questions