如何解决分解“列表”并分解并解压“词典列表”
我有如下结构的数据。简而言之,每当找到列表时,我都会尝试执行此操作 - 展开它,但是每当发现包含字典的列表时 - 展开它 AND 取消嵌套/解压密钥。
b = {
"_id" : "5f2","list1" : [
{
"dashbId" : 1019,"siteId" : 1
}
],"list2" : [1,2,3,4]
}
动态代码:
root = json_normalize(b)
x = (root.applymap(type) == list).all()
y = x.index[x].tolist()
nest_dict = ['[',']']
if len(y) == 0:
document = root
else:
for i in y:
m = str(root[i][0]).strip('[]')
if m[0] == '{' and m[-1] == '}':
if any(k in m for k in nest_dict) == True:
document = root
elif any(k in m for k in nest_dict) == False:
l = [root.drop(y,1),]
x = l.append(pd.json_normalize(b,record_path=i))
document= pd.concat(l,axis=1)
document= root.explode(i)
if (document[i].astype(str).str.isnumeric().all()) == True:
x = (document[i].to_frame().columns)
document[x] = document[x].fillna(0).astype(int)
print(document)
电流输出:
_id list1 list2
0 5f2 [{'dashbId': 1019,'siteId': 1}] 1
0 5f2 [{'dashbId': 1019,'siteId': 1}] 2
0 5f2 [{'dashbId': 1019,'siteId': 1}] 3
0 5f2 [{'dashbId': 1019,'siteId': 1}] 4
期望输出:
_id dashbId siteId list2
0 5f2 1019 1 1
0 5f2 1019 1 2
0 5f2 1019 1 3
0 5f2 1019 1 4
注意:代码中不能指定列名,必须是动态的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。