以显示的独特方式展平包含嵌套字典的列表的数据框列
Flatten the data frame column of list containing nested dictionaries in a unique way shown
以如下所示的方式展平嵌套字典列表的数据框列。
伙计们,我是 python 的新手,但我非常努力地实现目标,但不幸的是无法实现。
当前数据帧:
col1 col2
path1 [{sheetname1:{value11:length11,value12:length12,value13:length13...}},
{sheetname2:{value21:length21,value22:lenth22,...}}]
结果数据场:
col1 col2 col3 col4
path1 sheetname1 value11 length11
path1 sheetname1 value12 length12
path1 sheetname1 value13 length13
...
...
...
path1 sheetname2 value21 length21
path1 sheetname2 value22 length22
...
...
尝试:
data = []
for col1, row in zip(df["col1"], df["col2"]):
for d in row:
for k, v in d.items():
for kk, vv in v.items():
data.append({"col1": col1, "col2": k, "col3": kk, "col4": vv})
df = pd.DataFrame(data)
print(df)
打印:
col1 col2 col3 col4
0 path1 sheetname1 value11 length11
1 path1 sheetname1 value12 length12
2 path1 sheetname1 value13 length13
3 path1 sheetname2 value21 length21
4 path1 sheetname2 value22 lenth22
以如下所示的方式展平嵌套字典列表的数据框列。
伙计们,我是 python 的新手,但我非常努力地实现目标,但不幸的是无法实现。
当前数据帧:
col1 col2
path1 [{sheetname1:{value11:length11,value12:length12,value13:length13...}},
{sheetname2:{value21:length21,value22:lenth22,...}}]
结果数据场:
col1 col2 col3 col4
path1 sheetname1 value11 length11
path1 sheetname1 value12 length12
path1 sheetname1 value13 length13
...
...
...
path1 sheetname2 value21 length21
path1 sheetname2 value22 length22
...
...
尝试:
data = []
for col1, row in zip(df["col1"], df["col2"]):
for d in row:
for k, v in d.items():
for kk, vv in v.items():
data.append({"col1": col1, "col2": k, "col3": kk, "col4": vv})
df = pd.DataFrame(data)
print(df)
打印:
col1 col2 col3 col4
0 path1 sheetname1 value11 length11
1 path1 sheetname1 value12 length12
2 path1 sheetname1 value13 length13
3 path1 sheetname2 value21 length21
4 path1 sheetname2 value22 lenth22