Ana*_*gha 2 python group-by python-2.7 pandas cumsum
我需要在B列中重复的值,直到A列发生变化.
这是输入
Column A Column B
18 1
18 0
18 0
18 0
24 2
24 0
18 3
18 0
18 0
18 0
Run Code Online (Sandbox Code Playgroud)
预期产出
Column A Column B
18 1
18 1
18 1
18 1
24 2
24 2
18 3
18 3
18 3
18 3
Run Code Online (Sandbox Code Playgroud)
如果需要重复按移位列创建的每个组的第一个值,则可以使用transformby :firstSeriescumsumCol A
print (df['Col A'].ne(df['Col A'].shift()).cumsum())
0 1
1 1
2 1
3 1
4 2
5 2
6 3
7 3
8 3
9 3
Name: Col A, dtype: int32
df['Col B'] = df.groupby(df['Col A'].ne(df['Col A'].shift()).cumsum())['Col B']
.transform('first')
print (df)
Col A Col B
0 18 1
1 18 1
2 18 1
3 18 1
4 24 2
5 24 2
6 18 3
7 18 3
8 18 3
9 18 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
197 次 |
| 最近记录: |