Pandas groupby之后的列总数百分比

Pandas groupby之后的列总数百分比,pandas,pandas-groupby,Pandas,Pandas Groupby,尝试汇总pandas数据帧,并根据原始df的groupby结果计算“总计百分比”列 原始df: Shape_Area LU 0 91254232.781776 Fallow Cropland 1 522096.071094 Mixed Wetland Hardwoods 2 87795.467187 Mixed Wetland Hardwoods 3 440.528367 Mixed

尝试汇总pandas数据帧,并根据原始df的groupby结果计算“总计百分比”列

原始df:

        Shape_Area                       LU
0  91254232.781776          Fallow Cropland
1    522096.071094  Mixed Wetland Hardwoods
2     87795.467187  Mixed Wetland Hardwoods
3       440.528367  Mixed Wetland Hardwoods
4    778952.154436         Dikes and Levees
分组结果:

                              Shape_Area
LU                                      
Dikes and Levees           778952.154436
Fallow Cropland          91254232.781776
Mixed Wetland Hardwoods    610332.066649
我想为每种LU类型添加一个额外的“PCT of Total”列。我不确定是否正确访问了groupby结果,可能不理解它是什么(一个系列?)


您可以简单地计算
Shape\u区域
系列的总和(返回标量),然后将分组数据帧中
Shape\u区域
的每一行除以该值

grouped = df.groupby(['LU'])[['Shape_Area']].sum()
grouped['pct'] = grouped['Shape_Area'] / grouped['Shape_Area'].sum()

您可以简单地计算
Shape\u区域
系列的总和(返回标量),然后将分组数据帧中
Shape\u区域
的每一行除以该值

grouped = df.groupby(['LU'])[['Shape_Area']].sum()
grouped['pct'] = grouped['Shape_Area'] / grouped['Shape_Area'].sum()

我很讨厌这个论坛界面,它是如此该死的外国。我想也许我应该把.reset_index()应用到groupby中,然后我就可以在上面计算出一个pct total列了?我对这个论坛的UI很糟糕,太陌生了。我想也许我应该把.reset_index()应用到groupby,然后我就可以在上面计算出一个pct total列了?这就是我想要的。非常感谢。(再过几分钟就不能接受答案了。)这正是我想要的。非常感谢。(在几分钟内无法接受作为答案。)
                           Shape_Area       pct
LU                                             
Dikes and Levees         7.789522e+05  0.008408
Fallow Cropland          9.125423e+07  0.985004
Mixed Wetland Hardwoods  6.103321e+05  0.006588