【问题标题】:How to do the mean and group in Python? [duplicate]如何在 Python 中进行均值和分组? [复制]
【发布时间】:2021-12-05 16:25:12
【问题描述】:

我有以下几点:

table = [['Country', 'Points'], ['Spain', '7'], ['Spain', '9'], ['Germany', '1'], ['Germany', '3']]

我想取西班牙 (8) 和德国 (2) 的平均值并将它们分组到:

table_result = [['Country', 'Points'], ['Spain', '8'], ['Germany', '2']]

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:
import pandas as pd

table = [['Country', 'Points'], ['Spain', '7'], ['Spain', '9'], ['Germany', '1'], ['Germany', '3']]
df = pd.DataFrame(table[1:], columns=table[0])

df['Points'] = df['Points'].astype(int)
grouped_df = df.groupby('Country')
mean_df = grouped_df.mean()

输出:

print(mean_df)
         Points
Country        
Germany     2.0
Spain       8.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2015-06-04
    • 2020-10-31
    相关资源
    最近更新 更多