我有一个数据框,其中的一列填充有 1 和 0 组。如何为每个组指定从 1 开始的连续编号?
我尝试过跨行的 for 循环,但我需要列操作来提高性能。
d = {'col1': [1,1,1,0,0,1,1,0,0,0,1,1]}
df1 = pd.DataFrame(data=d)
df1
col1
0 1
1 1
2 1
3 0
4 0
5 1
6 1
7 0
8 0
9 0
10 1
11 1
我需要以下输出:
col1 col2
0 1 1
1 1 1
2 1 1
3 0 2
4 0 2
5 1 3
6 1 3
7 0 4
8 0 4
9 0 4
10 1 5
11 1 5
最佳答案
您可以比较移位值是否不相等,并通过 Series.cumsum
添加累积和。 :
df1['col2'] = df1['col1'].ne(df1['col1'].shift()).cumsum()
print (df1)
col1 col2
0 1 1
1 1 1
2 1 1
3 0 2
4 0 2
5 1 3
6 1 3
7 0 4
8 0 4
9 0 4
10 1 5
11 1 5
关于python - 拆分/分组 pandas 数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54441902/