how to group by keys with respect of some part of values in python?

浪尽此生 提交于 2021-01-29 09:00:22

问题


I have a json file with keys and Results . The result has 3 parts. like this:

df.json()[0]['Results'][0]

{'categoryId': '2674',
 'categoryName': 'software engineer',
 'score': '1.0377672767639161'}

I want to collect all keys who have the same categoryName in the result. and then count them. Is it possible?


回答1:


One way of doing it would be iterating over every group in one of the following ways: if you just want to know the count of one group you can do this:

category_name = "software engineer"
count = 0
for cat in df.json()[0]['Results']:
    if cat['categoryName'] == category_name:
        count += 1

If you want to count all categories at the same time you can do that as well:

category_count = {}
for cat in df.json()[0]['Results']:
   category = cat['categoryName']
   if category in category_count.keys():
       category_count[category] += 1
    else:
        category_count[category] = 1

to get the corresponding keys you can do:

category_count = {}
for key, cat in enumerate(df.json()[0]['Results']):
   category = cat['categoryName']
   if category in category_count.keys():
       category_count[category].append(key)
    else:
        category_count[category] = [key]

that way you can get all keys with the categoryName="software engineer" like this: category_count["software_engineer"]



来源:https://stackoverflow.com/questions/65794487/how-to-group-by-keys-with-respect-of-some-part-of-values-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!