[英]how to group by keys with respect of some part of values in python?
I have a json file with keys
and Results
.我有一个带有keys
和Results
的 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.