Python 计算数据帧中某些数字集的平均值(熊猫、蟒蛇3)

Python 计算数据帧中某些数字集的平均值(熊猫、蟒蛇3),python,pandas,Python,Pandas,我有这样一个数据帧: Group Importance 1 100% 1 100% 1 50% 2 75% 2 50% 我想对重要性进行标准化,因此对于每个组,合并的重要性等于100%(例如,每个单元格除以特定组中其余数字的总和) 例如: Group Importance Weight 1 100%

我有这样一个数据帧:

    Group    Importance
    1          100%
    1          100%
    1          50%  
    2          75%
    2          50%
我想对重要性进行标准化,因此对于每个组,合并的重要性等于100%(例如,每个单元格除以特定组中其余数字的总和)

例如:

  Group    Importance      Weight
    1          100%        100%/Sum(100%+100%+50%) = 40%
    1          100%        100%/Sum(100%+100%+50%) = 40%
    1          50%         50%/Sum(100%+100%+50%)  = 20%
因此,我正试图获得这样的输出:

  Group    Importance      Weight
    1          100%        40%
    1          100%        40%
    1          50%         20%
    2          100%        60%
    2          50%         40%
我最初的想法是尝试利用groupby中for循环的功能,但这是非常错误的,比如:

for z in df.groupby(['Group']):
    df.apply(lambda row: (row[1]/df['Importance'])

假设数据帧中的值是数字(例如,50对“50%”):

df['Weight'] = df.groupby('Group')['Importance'].transform(lambda x: x / sum(x))

>>> df
   Group  Importance  Weight
0      1        1.00     0.4
1      1        1.00     0.4
2      1        0.50     0.2
3      2        0.75     0.6
4      2        0.50     0.4