我有一个 JSON 对象,其中可能包含重复的项目和位置,并且我想保留风险最高的项目和位置(并且仅保留其中一个)
[{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'Low'
#Other values are omitted
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'High'
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'Moderate'
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'High'
},
{
'item': 'itemtwo',
'location': 'locationtwo',
'risk_level': 'Low'
}]
我尝试将其转换为 pandas 数据帧,根据risk_level对其进行排序并使用 drop_duplicates 但这会导致 JSON 中其他值出现问题(例如,将 None 转换为 NaN、将 int 转换为 float 等),所以我不这样做认为可行。
#Convert to dataframe and drop identical insights with lowest severities
dfInsights = pd.DataFrame(response['data'])
dfInsights = dfInsights.reindex(columns=list(response['data'][0].keys()))
dfInsights.sort_values(['risk_level'], inplace=True)
dfInsights.drop_duplicates(['item','location'], keep='first', inplace=True)
dfToJSON = dfInsights.to_dict(orient='records')
我希望结果是:
[{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'High'
},
{
'item': 'itemtwo',
'location': 'locationtwo',
'risk_level': 'Low'
}]
最佳答案
您可以利用 itertools.groupby
以及基于权重的自定义键函数:
d = [{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'Low'
#Other values are omitted
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'High'
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'Moderate'
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'High'
},
{
'item': 'itemtwo',
'location': 'locationtwo',
'risk_level': 'Low'
}]
from itertools import groupby
from operator import itemgetter
f = itemgetter('item', 'location')
weights = {'Low':2, 'Moderate':1, 'High':0}
out = []
for v, g in groupby(sorted(d, key=lambda k: (f(k), weights[k['risk_level']])), key=f):
out.append(next(g))
from pprint import pprint
pprint(out, width=30)
打印:
[{'item': 'itemone',
'location': 'locationone',
'risk_level': 'High'},
{'item': 'itemtwo',
'location': 'locationtwo',
'risk_level': 'Low'}]
关于Python - 根据 JSON 中的值从 JSON 中删除重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57086666/