0

I want to convert my dataframe to nested JSON so that I can use it to build my Mobile App. I need to make it nested. Level 0 will be brand. Level 1 will be model. Level 2 will be year. Level 3 will be rest of it. I have 6700 rows and 43 columns. And my dataframe looks like this. How to make it ?

enter image description here

3
  • Please post text and not images so that others can reproduce. Commented May 19, 2020 at 13:02
  • I don't know how do i do that. Like other persons who post it in grey back ground with small text size. Commented May 19, 2020 at 13:08
  • From the About page of pandas tag: See: How to make good reproducible pandas examples. Please read and use it. Another source of information is How to create a Minimal, Reproducible Example from the Help Center, specifically the page on code formatting. Docs are not to be ignored... Commented May 19, 2020 at 13:32

1 Answer 1

2

You could just do it by hand with nested dict comprehensions:

data = {brand: {model: {year: df.loc[(df['brand']==brand)&(df['model']==model)
                                 &(df['year']==year)].drop(
                                     columns=['brand', 'model', 'year']
                                     ).to_dict(orient='list') for year in
                        df.loc[(df['brand']==brand)&(df['model']==model), 'year']
                        .unique()} for model in df.loc[(df['brand']==brand),
                                                   'model']
                .unique()} for brand in df['brand'].unique()}

jsonstring = json.dumps(data)
Sign up to request clarification or add additional context in comments.

1 Comment

I'm really thankful for your help man. I appreciate it. My last question is , it holds data at last level like " AC heater 0: x " . X here is an float or integer but there are zeros on every line. Is that normal ? @Serge Ballesta

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.