gpt4 book ai didi

python - 将 pandas DataFrame 转换为具有最内层对象层的深度嵌套 JSON

转载 作者:行者123 更新时间:2023-12-02 03:23:17 25 4
gpt4 key购买 nike

假设我有一个 DataFrame df像:

source      tables      columns   data_type   length
src1 table1 col1 INT 4
src1 table1 col2 CHAR 2
src1 table2 col1 CHAR 2
src2 table1 col1 INT 4
src2 table1 col2 DATE 3

注意:DataFrame 还有另外 4 列与问题无关

需要类似于以下内容的输出:

{
"src1": {
"table1": {
"col1": {
"type": "INT"
"length": 4
},
"col2": {
"type": "CHAR"
"length": 2
}
},
"table2": {
"col1": {
"type": "CHAR"
"length": 2
}
}
},
"src2": {
"table1": {
"col1": {
"type": "INT"
"length": 4
},
"col2": {
"type": "DATE"
"length": 3
}
}
}
}

我当前拥有的代码产生与上面相同的输出,但排除了实际的数据类型值(即,我得到的是 "type": "CHAR" ,而不是 "type": "" ),因为我不确定我是如何' d 能够相应地嵌套值。这是代码:

def make_nested(df): 
f = lambda: defaultdict(f)
data = f()

for row in df.to_numpy().tolist():
t = data
for r in row[:-6]:
t = t[r]
t[row[-6]] = {
"type": '',
"length": ''
}

return data

我的问题是如何正确附加 data_typelength每个 columns 中的列值JSON 对象而不牺牲确切的格式?谢谢。

最佳答案

def make_nested(df): 
f = lambda: defaultdict(f)
data = f()

for row in df.to_numpy().tolist():
t = data
for r in row[:-3]:
t = t[r]
t[row[-3]] = {
"type": row[-2],
"length": row[-1]
}

return data

最后两列值位于第三级内,所以这就是您应该做的。

关于python - 将 pandas DataFrame 转换为具有最内层对象层的深度嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60493133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com