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

Saturday, July 23, 2022

[FIXED] How to concatenate this json object using pandas?

 July 23, 2022     json, pandas, python     No comments   

Issue

This is my json data:

{location: {city: 'San Francisco', state: 'CA', country: 'USA'}}

I wanna see this:

{location_city: 'San Francisco', location_state: 'CA', location_country: 'USA'}

How to do like this using pandas?


Solution

If there is a good reason for using pandas, one approach is to use json_normalize:

import pandas as pd

res = pd.json_normalize( {'location': {'city': 'San Francisco', 'state': 'CA', 'country': 'USA'}}, sep="_")
print(res)

Output

   location_city location_state location_country
0  San Francisco             CA              USA

Or, as an alternative you could write a function to flatten the dictionary:

def flatten_dict(d, sep="_", root=None):
    result = {}
    for key, value in d.items():
        k = f"{root}{sep}{key}" if root else key
        if isinstance(value, dict):
            k = f"{root}{sep}{key}" if root else key
            result.update(flatten_dict(value, root=k))
        else:
            result[k] = value
    return result


res = flatten_dict({'location': {'city': 'San Francisco', 'state': 'CA', 'country': 'USA'}})
print(res)

Output

{'location_city': 'San Francisco', 'location_state': 'CA', 'location_country': 'USA'}


Answered By - Dani Mesejo
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • 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