【问题标题】:How to say "if elements in the same column are the same, then calculate the average of corresponding values" in pandas如何在pandas中说“如果同一列中的元素相同,则计算对应值的平均值”
【发布时间】:2022-01-25 17:45:31
【问题描述】:
    origin_destination_country  average_delay_mins
0                       ALBANIA                0.00
1                       ALBANIA               13.68
2                       ALBANIA                0.00
3                       ALBANIA                0.00
4                       ALBANIA               79.50
...                         ...                 ...
6273                        USA                0.00
6274                 UZBEKISTAN               27.32
6275                     ZAMBIA               16.08
6276                   ZIMBABWE             1165.00
6277                   ZIMBABWE              102.97

如何计算每个国家/地区的 (average_delay_mins) 平均值?我的想法是计算与相似的 origin_destination_country 名称对应的值,并将它们存储在另一个没有重复国名的列表中。

【问题讨论】:

  • 使用groupby:df.groupby('origin_destination_country').mean()
  • 这就是我想要的。非常感谢

标签: python pandas


【解决方案1】:

试试这个代码,让我知道它是否有效。

import pandas as pd

df = pd.DataFrame({
    'origin_destination_country': ['ALBANIA', 'ALBANIA','ALBANIA', 'USA', 'ZIMBABWE', 'ZIMBABWE'],
    'average_delay_mins': [0.00, 13.68,0.00,0.00,1165.00,102.97]
})

#get unique country names
list_of_countries = df['origin_destination_country'].unique()

res = []
for i in range(len(list_of_countries)):
    #get series of identical country names
    get_series = df[df['origin_destination_country'] == list_of_countries[i]]['average_delay_mins'].tolist()
    res.append(sum(get_series) / len(get_series))

print(res)

【讨论】:

    【解决方案2】:

    感谢 Naufal_Hilmiaj 和 Code_Different 我只是设法找到了解决方案,它是这样的:

    import pandas as pd
    
    df = pd.DataFrame({
        'origin_destination_country': ['ALBANIA', 'ALBANIA','ALBANIA', 'USA', ...,'ZIMBABWE', 'ZIMBABWE'],
        'average_delay_mins': [0.00, 13.68,0.00,0.00,...,1165.00,102.97]
    })
    
    data = df.groupby('origin_destination_country').mean()
    print(data)
    
    

    【讨论】:

      猜你喜欢
      • 2019-01-28
      • 2022-01-08
      • 2022-08-17
      • 2013-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多