简体   繁体   English

如何针对 python 中的某些值按键分组?

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

I have a json file with keys and Results .我有一个带有keysResults的 json 文件。 The result has 3 parts.结果有 3 个部分。 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.我想收集结果中具有相同categoryName的所有keys and then count them.然后数一数。 Is it possible?可能吗?

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"]这样你就可以像这样获得categoryName="software engineer"的所有键: category_count["software_engineer"]

暂无
暂无

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

相关问题 如何根据每个元素中的某些信息对列表的元素进行分组? - how to group element's of a list with respect of some information in each elements? 如何在Python中针对列值删除行? - How to drop rows with respect to a column values in Python? 如何对列表信息的某些部分进行分组? - how to group some part of a list's information? 如何将字典的某些键分组为嵌套键? - How to group some keys of dictionary to nested key? 如何根据 Python3 中的另一个列表对列表中的元素进行分组? - How to group elements in a list in with respect to another list in Python3? 当鼠标移动到python中图形的某个部分并将其放在网页上时,如何绘制可以指示值的图形? - How to draw a graph that can indicate the values when the mouse moves to some part of the graph in python and put it on the web page? 如何使用 re.sub 根据 python 中的模式字典和替换值替换文本的某些部分? - How to substitute some part of a text based on a dictionary of patterns and substitute values in python using re.sub? 如何 plot 列出 python 中字典键的值 - How to plot list if values with respect to its key of a dictionary in python 如何从Python中的字典列表中获取某些键的不同值 - How to get distinct values for some certain keys from a list of dictionary in Python 如何将一列的值与 python 中另一列的值相加 - How to sum the values of one column with respect to a value of another column in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM