仅使用某个键从字典字典创建数据框

问题描述 投票:1回答:1

我有一个这样的字典词典列表:

d = [{'c1': {'ignore1': 'me1', 'use': 'me'},
      'c2': {'ignore2': 5., 'use': 12}},
     {'c1': {'ign': 2, 'use': 'me2', 'foo': 123},
      'c2': {'ignore2': 5., 'use': 14}}
    ]

并希望构建一个这样的数据帧:

    c1  c2
0   me  12
1  me2  14

所以我想只使用嵌套字典中的密钥use,主字典的键作为列名。

当我做

pd.DataFrame.from_records(d)

我收到

                                         c1                             c2
0       {u'use': u'me', u'ignore1': u'me1'}  {u'use': 12, u'ignore2': 5.0}
1  {u'ign': 2, u'use': u'me2', u'foo': 123}  {u'use': 14, u'ignore2': 5.0}

可能的解决方案可能如下所示:

df2 = pd.io.json.json_normalize(d).filter(regex='.use$')
df2.columns = df2.columns.str.replace('.use', "")

这给了我想要的结果。

是否有直接的方法来过滤所需的密钥,例如通过以不同的方式使用.from_records

python pandas dictionary
1个回答
1
投票

一种方法是操纵你的字典并在你的新字典上应用pd.DataFrame

d = [{'c1': {'ignore1': 'me1', 'use': 'me'},
      'c2': {'ignore2': 5., 'use': 12}},
     {'c1': {'ign': 2, 'use': 'me2', 'foo': 123},
      'c2': {'ignore2': 5., 'use': 14}}]

d2 = [{k: v['use'] for k, v in i.items()} for i in d]

# [{'c1': 'me', 'c2': 12}, {'c1': 'me2', 'c2': 14}]

df = pd.DataFrame(d2)

#     c1  c2
# 0   me  12
# 1  me2  14
© www.soinside.com 2019 - 2024. All rights reserved.