【问题标题】:Find an average for specific keys in the list of dictionaries在字典列表中查找特定键的平均值
【发布时间】: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


【解决方案1】:

您是否尝试过将数据传递到 Pandas DataFrame 并在那里使用它?

你可以这样做,首先制作一个DataFrame:

import pandas as pd
import numpy as np

d = {
    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}
}

#
df = pd.DataFrame(d).Transpose()

Out:
    country points  price
0   US      96      235
1   Spain   96      110
2   US      96      90
3   US      96      65

然后groupby国家

# just to make sure they are numeric
df[['points','price']] = df[['points','price']].astype('float64')

df.groupby('country').mean()

Out:
        points  price
country     
Spain   96.0    110.0
US      96.0    130.0

【讨论】:

  • 我的代码在 Pandas df 中。我已经在正文中编辑了我的代码。我现在正在努力将一本字典放入字典列表中。
猜你喜欢
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多