Pandas 提取数据帧中特定键值对的值
我有一个数据框,其中一列有嵌套dict的列表。我正在尝试获取与特定键相关的值 下面给出了Dataframe的外观:Pandas 提取数据帧中特定键值对的值,pandas,dictionary,Pandas,Dictionary,我有一个数据框,其中一列有嵌套dict的列表。我正在尝试获取与特定键相关的值 下面给出了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': '
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\u 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)
Edit:由于
sale\u detail
列的类型为string,我们需要首先将其转换为带有ast.literal\u eval(…)
的dict数组,谢谢您的帮助。然而,当我运行detail=df['sale\u detail']时,我得到了一个错误AttributeError:'str'对象没有属性'get'
。应用(get\u detail)。to\u list()
什么是类型(df.loc[0,'sale\u detail'])
打印?它返回str我明白了。很抱歉,我假设它是一个字典数组,感谢这导致另一个错误AttributeError:'Series'对象没有属性'to_list'
。。对不起,你有什么建议吗。。
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)