如何提取json对象中的特定值

2024-09-23 00:27:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我的json如下所示:

json_obj=[{'extracted_value':{'other':'Not found','sound':'false','longterm':'false','Medicine':'false','false','page_num':'33','score':'0.75','number':12223611,'misc':'true'}]

df=pd.DataFrame(json_obj)[['extracted_value','page_num','conf_score','number']

我只提取上述信息。但现在我想忽略“other”:“notfound”在extracted_value列中,然后像上面的值一样提取


Tags: jsonfalseobjnumbervaluepagenotnum
1条回答
网友
1楼 · 发布于 2024-09-23 00:27:38

您可以尝试 df['extracted_value'].apply(remove_other),即对列提取的值应用函数

完整代码为:

json_obj = [{'extracted_value': {'other': 'Not found', 'sound': 'false', 'longterm': 'false', 'physician': 'false'}, 'page_num': '33', 'score': '0.75', 'number': 12223611, 'misc':'true'}]
df=pd.DataFrame(json_obj)[['extracted_value', 'page_num','number']]

def remove_other(my_dict):
    return {e:my_dict[e]  for e in my_dict if  e != 'other' and my_dict[e] != 'Not Found' } # condition to remove other and not found pair
    
df['extracted_value']=df['extracted_value'].apply(remove_other)

结果将是:

extracted_value                                        page_num number
0   {'sound': 'false', 'longterm': 'false', 'physi...   33      12223611

其他答复:

  1. df['extracted_value'].apply(remove_other)表示列值将作为参数传递给函数。您可以将print语句print(my_dict)放在remove_other中以更好地可视化它

  2. 可以更改代码以从和条件中删除字典值

def remove_other(my_dict):
    return {e:my_dict[e]  for e in my_dict if  e != 'other' }#and my_dict[e] != 'Not Found' } # remove'other' key item 
    

我建议您熟悉JSON。在这种情况下,需要转到[0]['coord'][0]。因此,函数将类似于:

# Section_Page_start and Section_End_Page
def get_start_and_end(var1):
    my_dict=var1[0]['coord'][0]
    return {ek:my_dict[ek] for ek in my_dict if ek in ['Section_Page_start','Section_End_Page']}

相关问题 更多 >