【发布时间】:2019-08-28 13:43:31
【问题描述】:
我有一个包含以下键的字典列表:国家、积分、价格。我需要获得每个国家/地区的平均积分和价格。这是列表:
0: {country: "US", points: 96, price: 235}
1: {country: "Spain", points: 96, price: 110}
2: {country: "US", points: 96, price: 90}
3: {country: "US", points: 96, price: 65}
我需要一个带有国家和平均水平的字典列表。
我已经有了一个包含价格和积分总和的字典列表:
[{'country': 'Albania', 'points': 176, 'price': 40.0}, {'country': 'Argentina', 'points': 480488, 'price': 116181.0}, {'country': 'Australia', 'points': 430092, 'price': 152979.0}
现在我需要获取平均值。我正在考虑为 country.length 创建另一个键,然后在 for 循环中执行基本计算。但不确定这是否是正确的方法...感谢您的帮助!
我的代码如下:
count_dict = country_count.to_dict()
# Output
{'US': 62139,
'Italy': 18784,
'France': 14785,
'Spain': 8160}
# Get the sum of points and price for each country
grouped_data = wine_data.groupby('country').agg({'points':'sum', 'price':'sum'})
# Reset the index in order to convert df into a list of dictionaries
country_data = grouped_data.reset_index()
country_list = country_data.to_dict('records')
# Output
[{'country': 'Albania', 'points': 176, 'price': 40.0}, {'country': 'Argentina', 'points': 48048 etc]```
【问题讨论】:
-
你的意思是你有一个嵌套字典?
-
向我们展示您目前的代码...
-
@match
country_count = wine_data['country'].value_counts() count_dict = country_count.to_dict() # Output {'US': 62139, 'Italy': 18784, 'France': 14785, 'Spain': 8160} # Get the sum of points and price for each country grouped_data = wine_data.groupby('country').agg({'points':'sum', 'price':'sum'}) # Reset the index in order to convert df into a list of dictionaries country_data = grouped_data.reset_index() country_list = country_data.to_dict('records') # Output [{'country': 'Albania', 'points': 176, 'price': 40.0}, {'country': 'Argentina', 'points': 48048 etc] -
对分组的 wine_data 使用 agg 方法的地方,可以直接使用 mean 代替 sum:wine_data.groupby('country').agg({'points':'mean', 'price ':'意思'})
-
@CharlesGleason 我的代码过于复杂。你的方法正是我所需要的。非常感谢!
标签: python dictionary key