Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse of Pandas json_normalize

I just discovered the json_normalize function which works great in taking a JSON object and giving me a pandas Dataframe. Now I want the reverse operation which takes that same Dataframe and gives me a json (or json-like dictionary which I can easily turn to json) with the same structure as the original json.

Here's an example: https://hackersandslackers.com/json-into-pandas-dataframes/.

They take a JSON object (or JSON-like python dictionary) and turn it into a dataframe, but I now want to take that dataframe and turn it back into a JSON-like dictionary (to later dump to json file).

like image 513
Parsa T Avatar asked Feb 20 '19 00:02

Parsa T


2 Answers

A simpler approach:
Uses only 1 function...

def df_to_formatted_json(df, sep="."):
    """
    The opposite of json_normalize
    """
    result = []
    for idx, row in df.iterrows():
        parsed_row = {}
        for col_label,v in row.items():
            keys = col_label.split(".")

            current = parsed_row
            for i, k in enumerate(keys):
                if i==len(keys)-1:
                    current[k] = v
                else:
                    if k not in current.keys():
                        current[k] = {}
                    current = current[k]
        # save
        result.append(parsed_row)
    return result
like image 124
Yaakov Bressler Avatar answered Oct 11 '22 03:10

Yaakov Bressler


df.to_json(path)

or

df.to_dict()
like image 27
Dallas Lindauer Avatar answered Oct 11 '22 03:10

Dallas Lindauer