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

How to create a single json file from two DataFrames?

I have two DataFrames, and I want to post these DataFrames as json (to the web service) but first I have to concatenate them as json.

#first df
input_df = pd.DataFrame()
input_df['first'] = ['a', 'b']
input_df['second'] = [1, 2]

#second df
customer_df = pd.DataFrame()
customer_df['first'] = ['c']
customer_df['second'] = [3]

For converting to json, I used following code for each DataFrame;

df.to_json(
        path_or_buf='out.json',
        orient='records',  # other options are (split’, ‘records’, ‘index’, ‘columns’, ‘values’, ‘table’)
        date_format='iso',
        force_ascii=False,
        default_handler=None,
        lines=False, 
        indent=2    
    )

This code gives me the table like this: For ex, input_df export json

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

[
  {
    "first":"a",
    "second":1
  },
  {
    "first":"b",
    "second":2
  }
]

my desired output is like that:

{
  "input": [
    {
      "first": "a",
      "second": 1
    },
    {
      "first": "b",
      "second": 2
    }
  ],
  "customer": [
    {
      "first": "d",
      "second": 3
    }
  ]
}

How can I get this output like this? I couldn’t find the way 🙁

>Solution :

You can concatenate the DataFrames with appropriate key names, then groupby the keys and build dictionaries at each group; finally build a json string from the entire thing:

out = (
       pd.concat([input_df, customer_df], keys=['input', 'customer'])
       .droplevel(1)
       .groupby(level=0).apply(lambda x: x.to_dict('records'))
       .to_json()
      )

Output:

'{"customer":[{"first":"c","second":3}],"input":[{"first":"a","second":1},{"first":"b","second":2}]}'

or a dict by replacing the last to_json() to to_dict().

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