pandas - 在 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
解决方案
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(...)
.
推荐阅读
- javascript - 如何使 Django 模型和视图将 JSON 数据传递到 MySQL 数据库?
- xml - WSO2如何用大量数字填充属性值
- unity3d - 如何在unity 3d中停止旋转子孩子
- windows - 当文件与dockerfile位于不同的文件夹中时如何复制文件?
- c# - 选择表中的单行并将 id 发布到控制器
- angular - 在另一个完成后使一个可观察
- javascript - 不能在 nightwatch.js 中使用 setValue()
- javascript - “未捕获的 TypeError:无法读取 null 的属性 'toString'”
- bi-publisher - 带有@Inlines 的多个 IF 条件
- r - 选择有 2 个或更多的案例