如何在Python中按id分组,利用其他列上一行值计算新列
Pandas按组计算自定义收益率列
需求明确:给Pandas DataFrame按id分组后,计算新列new_col,公式为:new_col = 当前行a / (上一行a + 上一行b - 上一行c)
每组的第一行无需计算,留空(用NaN表示)。pct_change()仅支持单列计算,确实满足不了这种多列组合的跨行需求。
示例数据如下:
import pandas as pd df = pd.DataFrame({'id': ['Blue', 'Blue','Blue','Red','Red'], 'a':[100,200,300,1,2], 'b':[10,20,15,3,2], 'c':[1,2,3,4,5]}) print(df)
输出:
id a b c 0 Blue 100 10 1 1 Blue 200 20 2 2 Blue 300 15 3 3 Red 1 3 4 4 Red 2 2 5
解决方案
用groupby结合shift()方法就能实现,shift(1)可获取组内上一行的数据,完美适配分组后的跨行计算:
# 按id分组,计算每组内上一行的a+b-c作为分母 denominator = df.groupby('id')[['a', 'b', 'c']].shift(1).apply(lambda x: x['a'] + x['b'] - x['c'], axis=1) # 计算new_col:当前行a除以分母,第一行自动为NaN df['new_col'] = df['a'] / denominator print(df)
结果展示
输出结果完全符合预期:
id a b c new_col 0 Blue 100 10 1 NaN 1 Blue 200 20 2 1.826484 2 Blue 300 15 3 1.375573 3 Red 1 3 4 NaN 4 Red 2 2 5 inf
注:最后一行Red组的分母为1+3-4=0,因此得到inf(无穷大),实际场景可根据需求处理该情况,比如替换为NaN或其他值。
内容的提问来源于stack exchange,提问作者user3685918
相关产品推荐
相关产品推荐

