将pandas长格式表转换为嵌套json
我看过关于 to_json
和 json.dumps
的文档,也尝试了各种不同的索引和字典,但我有点迷糊了……我可以创建类似字典的名称-值对,但无法得到我需要的那种嵌套 JSON 格式。
我现在有一个 pandas 数据框,格式是这样的:
level_1 level_2 level_3 numeric
0 alpha one a 1
1 alpha one b 2
2 alpha two a 3
3 alpha two b 4
4 beta one a 5
5 beta one b 6
6 beta two a 7
7 beta two b 8
我需要一个 JSON 文件,格式如下:
{"alpha": {"one": {"a": 1, "b": 1}, "two": {"a": 3, "b": 4 etc...
1 个回答
6
这里有一个简单的例子,使用了提供的数据。
这个例子可以通过只使用Pandas数据框来改进,同时也可以动态处理列的数量。
import pandas as pd
import json
# Declare the nested dictionary that will hold the result
class NestedDict(dict):
def __missing__(self, key):
self[key] = NestedDict()
return self[key]
# Creation of the dataframe
df = pd.DataFrame({\
'level_1':['alpha' ,'alpha' ,'alpha' ,'alpha' ,'beta' ,'beta' ,'beta' ,'beta'],\
'level_2':['one' ,'one' ,'two' ,'two' ,'one' ,'one' ,'two' ,'two'],\
'level_3':['a' ,'b' ,'a' ,'b' ,'a' ,'b' ,'a' ,'b'],\
'numeric':[1 ,2 ,3 ,4 ,5 ,6 ,7 ,8]})
# Creation of a multi-index
rr = df.set_index(['level_1', 'level_2', 'level_3'])
d = NestedDict()
# Loop to store all elements of the dataframe in
# the instance of NestedDict
for k in rr.iterrows():
d[k[0][0]][k[0][1]][k[0][2]] = k[1].values[0]
# JSON output
json.dumps(d,default=str)