我有一个目录,看起来像这样:
source_dict = [{'ppl': 10, 'items': 15, 'airport': 'lax', 'city': 'Los Angeles', 'timestamp': 1, 'region': 'North America', 'country': 'United States'},
{'ppl': 20, 'items': 32, 'airport': 'JFK', 'city': 'New York', 'timestamp': 2, 'region': 'North America', 'country': 'United States'},
{'ppl': 50, 'items': 20, 'airport': 'ABC', 'city': 'London', 'timestamp': 1, 'region': 'Europe', 'country': 'United Kingdom'}... ]
#Gets the list of countries in the dict
countries = list(set(stats['country'] for stats in source_dict))
我知道我可以使用a系列:
counter = collections.Counter()
for d in source_dict:
counter.update(d)
但是,我们想按国家分组,只得到某些键的总数,而不是所有键的总数。你知道吗
所以结果应该是
{'Country': 'United States', 'p95': 30, 'items':37},
{'Country': 'England', 'ppl': 50, 'items':20},...
我不知道如何将多个键合并到一个计数器中。产生这样的结果
在熊猫中,您可以这样做:
这是一种使用
collections.defaultdict
&;collections.Counter
的方法。你知道吗例如:
输出:
相关问题 更多 >
编程相关推荐