如果 df 是你的数据框架,然后是类似的东西 df.groupby(['segment', 'time']).apply(lambda x: pd.Series({'total': x.weight.sum(), 'rate': (x.weight*x.score).sum()/x.weight.sum()})) 应该做的工作。例如,
df
df.groupby(['segment', 'time']).apply(lambda x: pd.Series({'total': x.weight.sum(), 'rate': (x.weight*x.score).sum()/x.weight.sum()}))
In [111]: df Out[111]: segment time weight score 0 A 0 10 30 1 B 1 20 40 2 A 0 30 50 3 B 1 40 60 In [112]: df.groupby(['segment', 'time']).apply(lambda x: pd.Series({'total': x.weight.sum(), 'rate': (x.weight*x.score).sum()/x.weight.sum()})) Out[112]: total rate segment time A 0 40.0 45.000000 B 1 60.0 53.333333