Python 通过未给出预期结果,使用组求和

Python 通过未给出预期结果,使用组求和,python,pandas,dataframe,sum,Python,Pandas,Dataframe,Sum,我需要在另一列上使用GROUPBY对一列的值求和,并用这些值覆盖数据帧 我试过了- df.groupby('S/T name')['Age group (Years)Total Persons'].sum() 要在其上实现sum的数据帧- S/T code S/T name city name population 1 NSW Greater sydney 1000 1

我需要在另一列上使用GROUPBY对一列的值求和,并用这些值覆盖数据帧

我试过了-

df.groupby('S/T name')['Age group (Years)Total Persons'].sum()
要在其上实现sum的数据帧-

S/T code        S/T name          city name         population
1                NSW            Greater sydney       1000
1                NSW            rest of nsw          100
1                NSW            rest of nsw          2000
2                Victoria       Geelong              1200
2                Victoria       Melbourne            1300
2                Victoria       Melbourne            1000
所需输出-

S/T code        S/T name        population
1                NSW                3100
2                Victoria           3500

请尝试以下代码:

解决方案1

grouped_df = df.groupby('S/T name')['population'].sum()
print(grouped_df)
上述代码将按列
S/T name
对结果进行分组,并给出
population
列的
sum

解决方案2

grouped_df1 = df.groupby('S/T name').agg({'S/Tcode':'unique','population': 'sum'})
grouped_df1

在您的示例中,您似乎在错误的列上求和,切换到“人口”将使您在大部分方面受益:

df.groupby('S/T name')['population'].sum()
因为您希望保留S/T code列,尽管您可以使用。在“人口”列中调用“总和”,在“S/T代码”列中调用“平均值”:

df.groupby('S/T name').agg({'population': 'sum', 'S/T code': 'mean'})
输出:

S/T name        S/T code  population              
NSW              1        3100
Victoria         2        3500

你得到了什么结果?