如何通过熊猫0.19.2中其他行的唯一对来标记行

ele*_*ora 1 python pandas

我有一个df这样的数据框,但更大。

  ID_0 ID_1  location
0    a    b     1
1    a    c     1
2    a    b     0
3    d    c     0
4    a    c     0
5    a    c     1
Run Code Online (Sandbox Code Playgroud)

我想添加一列来标识前两个。例如:

  ID_0 ID_1  location group_ID
0    a    b     1     0
1    a    c     1     1
2    a    b     0     0
3    d    c     0     2
4    a    c     0     1
5    a    c     1     1
Run Code Online (Sandbox Code Playgroud)

此新列来自映射“ ab”到0,“ ac”到1和“ dc”到2。

我认为第一步是

grouped  = df.groupby(['ID_0', 'ID_1'])
Run Code Online (Sandbox Code Playgroud)

但我不确定从那里去哪里。

您如何在熊猫中创建这个新专栏?

jez*_*ael 6

您需要GroupBy.ngroup,新的0.20.2

df['group_ID'] = df.groupby(['ID_0', 'ID_1']).ngroup()
print (df)
  ID_0 ID_1  location  group_ID
0    a    b         1         0
1    a    c         1         1
2    a    b         0         0
3    d    c         0         2
4    a    c         0         1
5    a    c         1         1
Run Code Online (Sandbox Code Playgroud)
df['group_ID'] = df.groupby(['ID_0', 'ID_1']).grouper.group_info[0]
print (df)
  ID_0 ID_1  location  group_ID
0    a    b         1         0
1    a    c         1         1
2    a    b         0         0
3    d    c         0         2
4    a    c         0         1
5    a    c         1         1
Run Code Online (Sandbox Code Playgroud)