使用apply
def sum_price(x): return x.sum() sums3 = df.groupby('color')['price','weight'].apply(lambda x:x.sum()).add_prefix('total_') sums4 = df.groupby('color')['price','weight'].apply(sum_price).add_prefix('total_') display(df,sums3,sums4) 输出: color item price weight 0 white luobo 4 4 1 white baicai 0 3 2 red lajiao 0 4 3 green donggua 7 5 4 white luobo 3 1 5 white baicai 3 3 6 red lajiao 0 6 7 green donggua 0 7 total_price total_weight color green 7 12 red 0 10 white 10 11 totals_price totals_weight color green 7 12 red 0 10 white 10 11数据分析之pandas常见的数据处理(四) (4)
内容版权声明:除非注明,否则皆为本站原创文章。