Skip to content

Instantly share code, notes, and snippets.

@vithalreddy
Created August 4, 2019 05:52
Show Gist options
  • Save vithalreddy/d6051feeb5a7de18bb8b46b4bbb5c332 to your computer and use it in GitHub Desktop.
Save vithalreddy/d6051feeb5a7de18bb8b46b4bbb5c332 to your computer and use it in GitHub Desktop.
Inverse of pandas json_normalize or json_denormalize – python pandas
# more at https://stackfame.com/inverse-of-pandas-json_normalize-or-json_denormalize-python-pandas
def make_formatted_dict(my_dict, key_arr, val):
"""
Set val at path in my_dict defined by the string (or serializable object) array key_arr
"""
current = my_dict
for i in range(len(key_arr)):
key = key_arr
if key not in current:
if i == len(key_arr)-1:
current = val
else:
current = {}
else:
if type(current) is not dict:
print("Given dictionary is not compatible with key structure requested")
raise ValueError("Dictionary key already occupied")
current = current
return my_dict
def df_to_formatted_json(df, sep="."):
result = []
for _, row in df.iterrows():
parsed_row = {}
for idx, val in row.iteritems():
keys = idx.split(sep)
parsed_row = make_formatted_dict(parsed_row, keys, val)
result.append(parsed_row)
return result
@mrtichou
Copy link

mrtichou commented Jul 30, 2023

pandas.Series.iteritems() method on line 25 is now deprecated. (See official pandas documentation)
You can use pandas.Series.items() instead ;)
Thanks for the code!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment