PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 24, 2022

[FIXED] How to generate a json file from dataframe concatenating columns

 July 24, 2022     json, jupyter-notebook, pandas     No comments   

Issue

I have this dataframe:

name        age
Paul        12
Andres      13
Caroline    14
Justin      15

I want to create a json file with the structure below:

{"NAME":["Paul","Andres","Caroline","Justin"], "NAME-AGE" :{"Paul":12,"Andres":13,"Caroline":14,"Justin":15},"VERSION":1}

I know I can use df.to_json() but I'm having a hard time to get the exactly output I want, including the version information.

What's the best approach to do it?


Solution

You can use:

d = {'NAME': df['name'].to_list(),
     'NAME-AGE': df.set_index('name')['age'].to_dict(),
     'VERSION': 1,
    }

import json

out = json.dumps(d)

output:

'{"NAME": ["Paul", "Andres", "Caroline", "Justin"], "NAME-AGE": {"Paul": 12, "Andres": 13, "Caroline": 14, "Justin": 15}, "VERSION": 1}'


Answered By - mozway
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing