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 ?
-
Please post text and not images so that others can reproduce.Serge Ballesta– Serge Ballesta2020-05-19 13:02:51 +00:00Commented 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.Fatih Can– Fatih Can2020-05-19 13:08:45 +00:00Commented 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...Serge Ballesta– Serge Ballesta2020-05-19 13:32:46 +00:00Commented May 19, 2020 at 13:32
Add a comment
|
1 Answer
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)
1 Comment
Fatih Can
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
