多索引熊猫的嵌套字典列表



我以嵌套字典列表的形式返回对Tableau的查询,其中包含值的列表。我想知道是否有可能以一种普遍的方式来解决这个问题。

I'm try to turn this

r = [{'name': 'TestWorkbook',
'embeddedDatasources': [{'name': 'Test1', 'id':'uuid1'},
{'name': 'Test2', 'id': 'uuid2'}],
'upstreamDatasources': [{'name': 'Test1', 'id': 'uuid1'}]},
{'name': 'TestWorkbook2',
'embeddedDatasources': [{'name': 'OtherTest', 'id': 'uuid3'}],
'upstreamDatasources': []}]

pd.DataFrame({('name', 'name'):['TestWorkbook', 'TestWorkbook', 'TestWorkbook2'], 
('embeddedDatasources', 'name'): ['Test1', 'Test2', 'OtherTest'], 
('embeddedDatasources', 'id'): ['uuid1', 'uuid2', 'uuid3'], 
('upstreamDatasources', 'name'): ['Test1', None, None], 
('upstreamDatasources', 'id'): ['uuid1', None, None], 
})

我可以用蛮力,但我必须对我想要的每个查询都这样做。(name/name位只是因为它没有多个级别)。即使有一个步骤可以让我达到80%,我也会喜欢。

编辑非常确定我要找的是pd.json_normalize,但会更新实际答案。

这不是您想要的,但它可能是一个很好的起点~

r = [{'name': 'TestWorkbook',
'embeddedDatasources': [{'name': 'Test1', 'id':'uuid1'},
{'name': 'Test2', 'id': 'uuid2'}],
'upstreamDatasources': [{'name': 'Test1', 'id': 'uuid1'}]},
{'name': 'TestWorkbook2',
'embeddedDatasources': [{'name': 'OtherTest', 'id': 'uuid3'}],
'upstreamDatasources': []}]
sources = ['upstreamDatasources', 'embeddedDatasources']
dfs = []
for source in sources:
df = pd.json_normalize(r, [source], ['name'], 'workbook_')
df['source'] = source
df = df.pivot(columns=['workbook_name', 'id'], index='source').T
dfs.append(df)
df = pd.concat(dfs).reset_index(-3, drop=True)

输出:

source              upstreamDatasources embeddedDatasources
workbook_name id
TestWorkbook  uuid1               Test1                 NaN
uuid1                 NaN               Test1
uuid2                 NaN               Test2
TestWorkbook2 uuid3                 NaN           OtherTest

最新更新