【发布时间】:2020-03-01 20:27:32
【问题描述】:
假设我有一个名为 df 的 pandas DataFrame,它看起来像:
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 层的任何帮助将不胜感激。提前谢谢你。
【问题讨论】:
标签: python json pandas dataframe object