首页 > 解决方案 > 在 Pandas Dataframe 中提取特定键值对的值

问题描述

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

下面给出的是 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

标签: pandasdictionary

解决方案


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

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(...).


推荐阅读