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

converting pandas dataframe to a custom JSON

This is my dataframe:

df = pd.DataFrame(
    {
        'a': ['x', 'x', 'y', 'y'],
        'b': ['xs', 'sx', 'rrx', 'ywer'],
        'c': ['aaa', 'bbb', 'rrsdrx', 'yz'],
    }
)

And this is the JSON output that I want:

{
    'x':{
        'links':[
            {
                'b': 'xs',
                'c': 'aaa'
            },
            {
                'b': 'sx',
                'c': 'bbb'
            }
        ]
    },

    'y':{
        'links':[
            {
                'b': 'rrx',
                'c': 'rrsdrx'
            },
            {
                'b': 'ywer',
                'c': 'yz'
            }
        ]
    },
}

I have tried the accepted answer of this post. And the following code was my other try:

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

x = df.groupby('a')['b'].apply(list).reset_index()
y = x.to_json(orient='records')
parsed = json.loads(y)
z = json.dumps(parsed, indent=4)

but the output was not what I needed.

>Solution :

Group the dataframe by a, then create dictionary for each dataframe for the keys, and create the required dictionary.

{k:{'links': d.drop(columns=['a']).to_dict('records')} for k,d in df.groupby('a')}

OUTPUT

{
  "x": {
    "links": [
      {
        "b": "xs",
        "c": "aaa"
      },
      {
        "b": "sx",
        "c": "bbb"
      }
    ]
  },
  "y": {
    "links": [
      {
        "b": "rrx",
        "c": "rrsdrx"
      },
      {
        "b": "ywer",
        "c": "yz"
      }
    ]
  }
}
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