Par*_*a T 10 json normalize python-3.x pandas
我刚刚发现了 json_normalize 函数,它在获取 JSON 对象并给我一个 Pandas Dataframe 方面效果很好。现在我想要反向操作,它采用相同的 Dataframe 并给我一个与原始 json 具有相同结构的 json(或类似 json 的字典,我可以很容易地转换为 json)。
这是一个示例:https : //hackersandslackers.com/json-into-pandas-dataframes/。
他们获取一个 JSON 对象(或类似 JSON 的 Python 字典)并将其转换为数据帧,但我现在想获取该数据帧并将其转换回类似 JSON 的字典(稍后转储到 json 文件)。
Par*_*a T 10
我用几个函数实现了它
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=".")
Run Code Online (Sandbox Code Playgroud)
更简单的方法:
仅使用 1 个函数...
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(sep)
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
Run Code Online (Sandbox Code Playgroud)