我的问题基本上与这个问题相反:
Create a Pandas DataFrame from deeply nested JSON
我想知道是否可以进行相反的操作。给定一个表格:
Library Level School Major 2013 Total
200 MS_AVERY UGRAD GENERAL STUDIES GEST 5079
201 MS_AVERY UGRAD GENERAL STUDIES HIST 5
202 MS_AVERY UGRAD GENERAL STUDIES MELC 2
203 MS_AVERY UGRAD GENERAL STUDIES PHIL 10
204 MS_AVERY UGRAD GENERAL STUDIES PHYS 1
205 MS_AVERY UGRAD GENERAL STUDIES POLS 53
是否可以生成嵌套的字典(或 JSON),例如:
字典:
{'MS_AVERY':
{ 'UGRAD' :
{'GENERAL STUDIES' : {'GEST' : 5}
{'MELC' : 2}
...
最佳答案
创建一个函数似乎并不难,它将根据您的 DataFrame
对象构建递归字典:
def fdrec(df):
drec = dict()
ncols = df.values.shape[1]
for line in df.values:
d = drec
for j, col in enumerate(line[:-1]):
if not col in d.keys():
if j != ncols-2:
d[col] = {}
d = d[col]
else:
d[col] = line[-1]
else:
if j!= ncols-2:
d = d[col]
return drec
这将产生:
{'MS_AVERY':
{'UGRAD':
{'GENERAL STUDIES': {'PHYS': 1L,
'POLS': 53L,
'PHIL': 10L,
'HIST': 5L,
'MELC': 2L,
'GEST': 5079L}}}}
关于python - Pandas 将 Dataframe 转换为嵌套的 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23576869/