【问题标题】:Returning a list of dictionary keys in a dataframe返回数据框中的字典键列表
【发布时间】:2021-11-24 14:01:12
【问题描述】:

我的数据框:

    _id      answers                                                                                                 
    a       [{'title': 'dog', 'value': True},
            {'title': 'cat', 'value': False},                
            {'title': 'bird', 'value': False}]              
    b       [{'title': 'food', 'value': False},                   
            {'title': 'water', 'value': True}, 
            {'title': 'wine', 'value': False}]               
    c       []                                                  
                                                                 
    d       [] 

我想构建一个包含键列表的额外列:

[dog, cat, bird]
[food, water, wine]
[]
[]          

理论上可以使用:

def getList(dict):
    return dict.keys()

但是当我实际上有一个字典列表而不是字典时,如何迭代数据框元素?

【问题讨论】:

    标签: python pandas list dataframe dictionary


    【解决方案1】:

    我认为您需要来自字典列表的 title 值:

    df['keys'] = df['answers'].apply(lambda x: [y['title'] for y in x])
    

    替代方案:

    df['keys'] = [[y['title'] for y in x ] for x in df['answers']]
    

    print (df)
                                                 answers                 keys
    0  [{'title': 'dog', 'value': True}, {'title': 'c...     [dog, cat, bird]
    1  [{'title': 'food', 'value': True}, {'title': '...  [food, water, wine]
    2                                                 []                   []
    3                                                 []                   []
    

    对于键输出不同:

    df['keys'] = df['answers'].apply(lambda x: [y.keys() for y in x])
    print (df)
                                                 answers  \
    0  [{'title': 'dog', 'value': True}, {'title': 'c...   
    1  [{'title': 'food', 'value': True}, {'title': '...   
    2                                                 []   
    3                                                 []   
    
                                                   keys  
    0  [(title, value), (title, value), (title, value)]  
    1  [(title, value), (title, value), (title, value)]  
    2                                                []  
    3                                                []  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-05
      • 1970-01-01
      • 2018-05-03
      • 2020-02-04
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      相关资源
      最近更新 更多