【问题标题】:Extracting values for a specific key-value pair in Pandas Dataframe在 Pandas Dataframe 中提取特定键值对的值
【发布时间】:2020-05-12 22:16:07
【问题描述】:

我有一个数据框,其中一列有一个嵌套字典列表。我正在尝试获取与特定键有关的值。

下面是 Dataframe 的样子:

sale_id, sale_detail
10001, [{
         'compulsory_on_complete': True,
         'name': 'Store Location',  <-- Pull value corresponding to this as given in the next row
         'value': 'London',   
         'value_id': 2}, 
        {
         'compulsory_on_complete': True,
         'name': 'Product Category', <-- Pull value corresponding to this as given in the next row
         'value': 'General',
         'value_id': 5}] 
10002, [{
         'compulsory_on_complete': True,
         'name': 'Store Location',
         'value': 'Scotland',
         'value_id': 2}, 
        {
         'compulsory_on_complete': True,
         'name': 'Product Category',
         'value': 'Supplies',
         'value_id': 5}] 

预期输出:

sale_id, store_location, product_category
10001, London, General
10002, Scotland, Supplies

【问题讨论】:

    标签: pandas dictionary


    【解决方案1】:

    sale_detail 列上运行apply 以提取数据:

    import ast
    
    def get_detail(sale_detail):
        result = {}
        for detail in ast.literal_eval(sale_detail):
            if detail.get('name') == 'Store Location':
                result['store_location'] = detail.get('value')
            elif detail.get('name') == 'Product Category':
                result['product_category'] = detail.get('value')
    
        return result
    
    detail = df['sale_detail'].apply(get_detail).to_list()
    pd.concat([df, pd.DataFrame(detail)], axis=1)
    

    编辑:由于sale_detail列是字符串类型,我们需要先将其转换为带有ast.literal_eval(...)的dicts数组。

    【讨论】:

    • 感谢您的帮助。但是,当我运行 detail = df['sale_detail'].apply(get_detail).to_list() 时,我收到错误 AttributeError: 'str' object has no attribute 'get'
    • type(df.loc[0, 'sale_detail']) 打印什么?
    • 它返回str
    • 啊,我明白了。抱歉,我以为是字典数组
    • 感谢这又出现了一个错误AttributeError: 'Series' object has no attribute 'to_list'.. 抱歉,对此有任何建议..
    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 2018-08-13
    • 2021-06-03
    • 2018-01-22
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多