如何迭代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":[]},
我想获得最高分的意图。
答案 0 :(得分:2)
您可以将'intents'
的值(dicts列表)转换为DataFrame
,然后使用argmax
:
df = pd.DataFrame(Response["intents"])
它的输出是:
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
然后是最大值:
df.iloc[df['score'].argmax(),:]
这将返回:
intent greeting
score 0.941468
Name: 0, dtype: object
答案 1 :(得分:0)
我确定还有特定的pandas方法,但另一个选择是提取字典并将其排序为通用字典。
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]
答案 2 :(得分:0)
试试这个: -
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