作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有一个 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_type
和length
每个 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/
我是一名优秀的程序员,十分优秀!