## 熊猫根据一栏分类的指标计算差异内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (28)

``````a b k
0 0 0
0 1 1
0 2 0
0 3 0
0 4 1
0 5 0
1 0 0
1 1 1
1 2 0
1 3 1
1 4 0
``````

``````a b k diff_b
0 0 0 nan
0 1 1 nan
0 2 0 1
0 3 0 2
0 4 1 3
0 5 0 1
1 0 0 nan
1 1 1 nan
1 2 0 1
1 3 1 2
1 4 0 1
``````

### 2 个回答

``````df['New']=df.b.loc[df.k==1]# get all value b when k equal to 1
df.New=df.groupby('a').New.apply(lambda x : x.ffill().shift()) # fillna by froward method , then we need shift.
df.b-df['New']# yield
Out[260]:
0     NaN
1     NaN
2     1.0
3     2.0
4     3.0
5     1.0
6     NaN
7     NaN
8     1.0
9     2.0
10    1.0
dtype: float64``````

``````parts = df.groupby('a').k.apply(lambda x: x.shift().cumsum())
``````

``````vals = df.groupby([df.a, parts]).b.apply(lambda x: x-x.min()+1)
``````

``````df['diff_b'] = np.select([parts!=0], [vals], np.nan)
``````

``````    a  b  k  diff_b
0   0  0  0     NaN
1   0  1  1     NaN
2   0  2  0     1.0
3   0  3  0     2.0
4   0  4  1     3.0
5   0  5  0     1.0
6   1  0  0     NaN
7   1  1  1     NaN
8   1  2  0     1.0
9   1  3  1     2.0
10  1  4  0     1.0
``````