Home > Software engineering >  pandas dataframe as as json file using index value
pandas dataframe as as json file using index value

Time:09-28

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'...])

CodePudding user response:

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)
  • Related