简体   繁体   English

遍历pandas数据框中的词典列表字典

[英]iterate over a dictionary of list of dictionaries in pandas dataframe

How to iterate over a dictionary of list of dictionaries in pandas dataframe one of the column is Response. 如何在pandas数据帧中的字典列表的字典上进行迭代,该列之一是Response。

Response = {"query":"hi","intents":[{"intent":"greeting","score":0.941468239},{"intent":"sentinel","score":7.298465E-06},{"intent":"analyticsPage","score":3.77489937E-06},{"intent":"KaaraServices","score":0.0251461584},{"intent":"goodBye","score":0.357869864},{"intent":"servicesPage","score":2.3839857E-05},{"intent":"PredAnalytics","score":3.21742641E-06},{"intent":"ykaara","score":0.006888155},{"intent":"creator","score":0.061054837}],"entities":[]}, 

I want to get the intent with the maximum score. 我想获得最高分的意图。

You can turn the value (the list of dicts) of 'intents' into a DataFrame and then use argmax : 您可以将'intents'的值( DataFrame列表)转换为DataFrame ,然后使用argmax

df = pd.DataFrame(Response["intents"])

Its output is: 其输出为:

          intent     score
0       greeting  0.941468
1       sentinel  0.000007
2  analyticsPage  0.000004
3  KaaraServices  0.025146
4        goodBye  0.357870
5   servicesPage  0.000024
6  PredAnalytics  0.000003
7         ykaara  0.006888
8        creator  0.061055

And then for the max: 然后最大:

df.iloc[df['score'].argmax(),:]

this will return: 这将返回:

intent    greeting
score     0.941468
Name: 0, dtype: object

I'm sure there's also pandas specific way(s) to do it, but another option is to extract the dictionary and sort it like a generic dictionary. 我敢肯定,还有做熊猫的特定方法,但是另一种选择是提取字典并像普通字典一样对它进行排序。

from operator import itemgetter

# Get pandas frame from somewhere
response = getresponse()

# Convert list of dictionary to dictionary
d = {}
for item in response["intents"]:
    d[item["intent"]] = item["score"]

# Sort dictionary, get highest scoring element
sorted(d.items(), key=itemgetter(1), reverse=True)[0]

Try this:- 尝试这个:-

Response = {"query":"hi","intents":[{"intent":"greeting","score":0.941468239},{"intent":"sentinel","score":7.298465E-06},\
{"intent":"analyticsPage","score":3.77489937E-06},{"intent":"KaaraServices","score":0.0251461584},\
{"intent":"goodBye","score":0.357869864},{"intent":"servicesPage","score":2.3839857E-05},\
{"intent":"PredAnalytics","score":3.21742641E-06},{"intent":"ykaara","score":0.006888155},\
{"intent":"creator","score":0.061054837}],"entities":[]},
max_score = []
for i in Response:
    for j in i['intents']:
        max_score.append(j['score'])
print(max(max_score)) #your expected outpu

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM