假设我有一个熊猫DataFrame df
,看起来像这样:
source tables columns
src1 table1 col1
src1 table1 col2
src1 table2 col1
src2 table1 col1
src2 table1 col2
我下面的当前代码可以遍历源列表并将每个源内的表列表嵌套为对象:
data = [
{k: v}
for k, v in df.groupby('source')['tables'].agg(
lambda x: {v: {} for v in x}).items()
]
with open('data.json', 'w') as f:
json.dump(data, f, indent = 2)
我通过此代码收到的输出如下:
[
{
"src1": {
"table1": {},
"table2": {}
}
},
{
"src2": {
"table1": {},
}
}
]
我想要的输出:
[
{
"src1": {
"table1": {
"col1": {},
"col2": {}
},
"table2": {
"col1": {}
}
}
},
{
"src2": {
"table1": {
"col1": {}
}
}
}
]
如上所示,将我的2层嵌套JSON文件转换为3层的任何帮助将不胜感激。先感谢您。
由于您在此处具有多个分组级别,因此建议您仅使用for循环对数据进行迭代。
from collections import defaultdict
def make_nested(df):
f = lambda: defaultdict(f)
data = f()
for row in df.to_numpy().tolist():
t = data
for r in row[:-1]:
t = t[r]
t[row[-1]] = {}
return data
print(json.dumps(make_nested(df), indent=2))
{
"src1": {
"table1": {
"col1": {},
"col2": {}
},
"table2": {
"col1": {}
}
},
"src2": {
"table1": {
"col1": {},
"col2": {}
}
}
}
假设您的列从左到右排列:最外键到最内键。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句