Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas dataframe as as json file using index value

I have a pandas dataframes created by groupby as below:
airbus_df.groupby([‘mfr’]).apply(lambda row: row.to_json(orient=’records’)).to_frame()
output looks like:

         0
mfr 
AIRBUS  [{"mfr mdl code":"3940005","icao":"A00C7A","se...
AIRBUS CANADA LTD PTNRSP    [{"mfr mdl code":"1400010","icao":"A062EC","se...
AIRBUS HELICOPTERS DEUTSCHLAND  [{"mfr mdl code":"5620040","icao":"A32422","se...
AIRBUS HELICOPTERS INC  [{"mfr mdl code":"1145005","icao":"A1F846","se...
AIRBUS INDUSTRIE    [{"mfr mdl code":"3930402","icao":"A009A4","se...
AIRBUS SAS  [{"mfr mdl code":"3940312","icao":"A3AD89","se

I wanted to create a json file for each ‘mfr’.
How do I save as json using index name.

df_t.index:
Index(['AIRBUS','AIRBUS CANADA LTD PTNRSP'...])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can loop by Series and write json to file by keys from index values:

import json

for k,v in airbus_df.groupby('mfr').apply(lambda row:row.to_json(orient='records')).items():
        with open(f"{k}.json", 'w') as f: 
            json.dump(v, f)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading