如何解决对子DataFrame重复DataFrame行
来源是带有嵌套字典的JSON文件。
我创建了一个顶层的defaultdict(dict)和一个for循环,以获取第1至7行,State,Size,Pop列的数据帧。
在上面的for循环中,我再次创建了另一个(子级)defaultdict(dict)和for循环,以获取第1至2行,City,Size,Pop列的数据框
我将孩子defaultdict(dict)附加到顶部defaultdict(dict)
父数据帧中的行应针对子DataFrame重复
所需的输出
State Size Pop City Size Pop
1 MH 120 300 MU 100 150
2 MH 120 300 PU 80 110
3 MH 120 300 NG 75 120
4 MH 120 300 PC 85 110
5 GJ 110 250 SU 70 100
6 GJ 110 250 VA 75 80
7 GJ 110 250 AH 85 120
另一个带有输入JSON的示例
输入JSON:
{
"datatop": [
{
"datastate": {
"attributes": {
"Name": "ABC","Place": "123"
},"children": [
{
"datacity": {
"attributes": {
"CName": "EFG","CPlace": "12345"
}
}
},{
"datacity": {
"attributes": {
"CNAME": "HIJ","CPlace": "6789"
}
}
}
]
}
},{
"datastate": {
"attributes": {
"Name": "XYZ","Place": "456"
},"children": [
{
"datacity": {
"attributes": {
"CName": "LMN","CPlace": "1123"
}
}
},{
"datacity": {
"attributes": {
"CName": "OPQ","CPlace": "22345"
}
}
}
]
}
}
],"totalCount": "2"
}
预期输出:
Name Place CName CPlace
ABC 123 EFG 12345
ABC 123 HIJ 6798
XYZ 456 LMN 1123
XYZ 456 OPQ 22345
解决方法
通过更改方法,我能够实现预期的输出。
之前,我试图对子数据循环中的数据帧中的行重复父数据帧中的行(我从父for循环中获得的行)。
新方法: 在父for循环之前创建了一个空列表。 将父级的键值对添加到子级的循环中,并创建了一个大字典,其中包含父级和子级(嵌套)的键值对。为了创建唯一键,我使用了父级和子级索引的字符串串联进行循环。 一旦子for循环结束,在其外部(在父for循环的末尾),我将字典转换为数据帧并将其附加到列表中。 父for循环完成后,列表即会完成,并带有数据帧。 最后,我对列表中的数据帧进行了串联。
import json
import pandas as pd
from collections import defaultdict
with open("./input.json") as file:
filedata = json.load(file)
data = filedata['datatop']
dflist = []
for i in range (len(data)):
attribute = (data[i])['datastate']['attributes']
child = (((data[i]['datastate'])['children']))
def_dct_chd = defaultdict(dict)
# For Loop to Iterate over all the subnets of the L3OUT EPG
for j in range (len(child)):
def_dct_chd[str(i)+str(j)]['Name'] = attribute['Name']
def_dct_chd[str(i)+str(j)]['Place'] = attribute['Place']
def_dct_chd[str(i)+str(j)]['CName'] = child[j]['datacity']['attributes']['CName']
def_dct_chd[str(i)+str(j)]['CPlace'] = child[j]['datacity']['attributes']['CPlace']
# Create the Data Frames out of the dictionary and append it to the list
dflist.append(pd.DataFrame(def_dct_chd).T)
# concatenate all the dictionaries inside the list
finaldf = pd.concat(dflist)
finaldf = finaldf.reset_index(drop=True)
print(finaldf)