我有以下数据框:

df1
    a   b
4   0   1
5   0   1
6   0   2
2   0   3
3   1   2
15  1   3
12  1   3
13  1   1
15  3   1
14  3   1
8   3   1
9   3   1
10  3   2
我需要另一列,以a,b分组,并在a的每组中交替分配值1,2,始终从1开始。
它看起来应该像这样:
    a   b   c
4   0   1   1
5   0   1   1
6   0   2   2
2   0   3   1
3   1   2   1
15  1   3   2
12  1   3   2
13  1   1   1
15  3   1   1
14  3   1   1
8   3   1   1
9   3   1   1
10  3   2   2

最佳答案

一种方法可能是 groupby ,采用基本上枚举每个组的 ngroup ,然后采用2模为模,然后使用结果从12进行索引:

import numpy
df['c'] = np.array([1,2])[df.groupby(['a','b']).ngroup().values%2]
print(df)

    a  b  c
4   0  1  1
5   0  1  1
6   0  2  2
2   1  2  1
3   1  3  2
15  1  3  2
12  1  3  2
13  1  4  1
15  3  1  2
14  3  1  2
8   3  1  2
9   3  1  2

更新,以便现在a中的每个组都以1开头(适应@wen的答案):
df['c'] = df.groupby('a').b.transform(lambda x : x.factorize()[0]%2+1)

print(df)

    a  b  c
4   0  1  1
5   0  1  1
6   0  2  2
2   0  3  1
3   1  2  1
15  1  3  2
12  1  3  2
13  1  1  1
15  3  1  1
14  3  1  1
8   3  1  1
9   3  1  1
10  3  2  2

10-06 05:17
查看更多