pandas 逆json_normalize [英] Inverse of Pandas json_normalize
问题描述
我刚刚发现了json_normalize函数,该函数在获取JSON对象并给我一个Pandas Dataframe时效果很好.现在,我想要反向操作,该操作采用相同的Dataframe并给我一个与原始json具有相同结构的json(或类似json的字典,我可以轻松地将其转换为json).
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.
这里是一个示例: https://hackersandslackers.com/json-into-pandas-数据帧/.
他们采用JSON对象(或类似JSON的python字典)并将其转换为数据框,但是我现在想采用该数据框并将其转换回类似JSON的字典(以便以后转储至json文件).
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).
推荐答案
我通过几个函数实现了它
I implemented it with a couple functions
def set_for_keys(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[i]
if key not in current:
if i==len(key_arr)-1:
current[key] = val
else:
current[key] = {}
else:
if type(current[key]) is not dict:
print("Given dictionary is not compatible with key structure requested")
raise ValueError("Dictionary key already occupied")
current = current[key]
return my_dict
def 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 = set_for_keys(parsed_row, keys, val)
result.append(parsed_row)
return result
#Where df was parsed from json-dict using json_normalize
to_formatted_json(df, sep=".")
这篇关于 pandas 逆json_normalize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!