如何根据另一列中的值创建唯一 ID
How can I create unique id based on the value in the other column
我想根据列中的值分配唯一 ID。对于前。我有一个 table 这样的:
df = pd.DataFrame({'A': [0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1]}
最终我希望我的输出 table 看起来像这样:
A
id
1
0
1
2
0
1
3
0
1
4
0
1
5
0
1
6
0
1
7
1
2
8
1
2
9
1
2
10
1
2
11
1
2
12
1
2
13
0
3
14
0
3
15
0
3
16
0
3
17
0
3
18
0
3
19
1
4
20
1
4
21
1
4
22
0
5
23
0
5
24
0
5
25
0
5
26
1
6
27
1
6
28
1
6
我尝试了 data.groupby(['a'], sort=False).ngroup() + 1
,但它并没有像我想要的那样工作。任何帮助和指导将不胜感激!谢谢!
diff
+ cumsum
:
df['id'] = df.A.diff().ne(0).cumsum()
df
A id
0 0 1
1 0 1
2 0 1
3 0 1
4 0 1
5 0 1
6 0 1
7 1 2
8 1 2
9 1 2
10 1 2
11 1 2
12 1 2
13 0 3
14 0 3
15 0 3
16 0 3
17 0 3
18 0 3
19 1 4
20 1 4
21 1 4
22 0 5
23 0 5
24 0 5
25 0 5
26 1 6
27 1 6
28 1 6
import pdrle
df["id"] = pdrle.get_id(df["A"]) + 1
df
# A id
# 0 0 1
# 1 0 1
# 2 0 1
# 3 0 1
# 4 0 1
# 5 0 1
# 6 0 1
# 7 1 2
# 8 1 2
# 9 1 2
# 10 1 2
# 11 1 2
# 12 1 2
# 13 0 3
# 14 0 3
# 15 0 3
# 16 0 3
# 17 0 3
# 18 0 3
# 19 1 4
# 20 1 4
# 21 1 4
# 22 0 5
# 23 0 5
# 24 0 5
# 25 0 5
# 26 1 6
# 27 1 6
# 28 1 6
我想根据列中的值分配唯一 ID。对于前。我有一个 table 这样的:
df = pd.DataFrame({'A': [0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1]}
最终我希望我的输出 table 看起来像这样:
A | id | |
---|---|---|
1 | 0 | 1 |
2 | 0 | 1 |
3 | 0 | 1 |
4 | 0 | 1 |
5 | 0 | 1 |
6 | 0 | 1 |
7 | 1 | 2 |
8 | 1 | 2 |
9 | 1 | 2 |
10 | 1 | 2 |
11 | 1 | 2 |
12 | 1 | 2 |
13 | 0 | 3 |
14 | 0 | 3 |
15 | 0 | 3 |
16 | 0 | 3 |
17 | 0 | 3 |
18 | 0 | 3 |
19 | 1 | 4 |
20 | 1 | 4 |
21 | 1 | 4 |
22 | 0 | 5 |
23 | 0 | 5 |
24 | 0 | 5 |
25 | 0 | 5 |
26 | 1 | 6 |
27 | 1 | 6 |
28 | 1 | 6 |
我尝试了 data.groupby(['a'], sort=False).ngroup() + 1
,但它并没有像我想要的那样工作。任何帮助和指导将不胜感激!谢谢!
diff
+ cumsum
:
df['id'] = df.A.diff().ne(0).cumsum()
df
A id
0 0 1
1 0 1
2 0 1
3 0 1
4 0 1
5 0 1
6 0 1
7 1 2
8 1 2
9 1 2
10 1 2
11 1 2
12 1 2
13 0 3
14 0 3
15 0 3
16 0 3
17 0 3
18 0 3
19 1 4
20 1 4
21 1 4
22 0 5
23 0 5
24 0 5
25 0 5
26 1 6
27 1 6
28 1 6
import pdrle
df["id"] = pdrle.get_id(df["A"]) + 1
df
# A id
# 0 0 1
# 1 0 1
# 2 0 1
# 3 0 1
# 4 0 1
# 5 0 1
# 6 0 1
# 7 1 2
# 8 1 2
# 9 1 2
# 10 1 2
# 11 1 2
# 12 1 2
# 13 0 3
# 14 0 3
# 15 0 3
# 16 0 3
# 17 0 3
# 18 0 3
# 19 1 4
# 20 1 4
# 21 1 4
# 22 0 5
# 23 0 5
# 24 0 5
# 25 0 5
# 26 1 6
# 27 1 6
# 28 1 6