Python 在dataframe列中查找相关值

Python 在dataframe列中查找相关值,python,pandas,dataframe,pandas-groupby,Python,Pandas,Dataframe,Pandas Groupby,我有一个带有ID、名称和标志的数据帧 我想创建一个新列,在其中填写相关ID 以下是一些规则: 如果标志='0'或'A',则没有相关id 如果标志='B',我们需要找到相同的名称(减去名称中的标志),但带有标志'A',并获得id 如果标志='C',我们需要找到相同的名称(减去名称中的标志),但带有标志'B',并获得id 以下是DF的代码: import pandas as pd d = {'name': ['test1 A', 'test1 B', 'test2 A', 'test2 B',

我有一个带有ID、名称和标志的数据帧

我想创建一个新列,在其中填写相关ID

以下是一些规则:

  • 如果标志='0'或'A',则没有相关id
  • 如果标志='B',我们需要找到相同的名称(减去名称中的标志),但带有标志'A',并获得id
  • 如果标志='C',我们需要找到相同的名称(减去名称中的标志),但带有标志'B',并获得id
以下是DF的代码:

import pandas as pd

d = {'name': ['test1 A', 'test1 B', 'test2 A', 'test2 B', 'test3','test4 A','test4 B','test4 C'],
     'id': [1, 2, 3, 4, 5, 6, 7, 8],
     'flag': ['A', 'B', 'A', 'B', '0', 'A', 'B', 'C']}
df = pd.DataFrame(data=d)
这是期望的结果:

name        id     flag    related id
test1 A      1        A           nan
test1 B      2        B           1
test2 A      3        A           nan
test2 B      4        B           3
test3 0      5        0           nan
test4 A      6        A           nan
test4 B      7        B           6
test4 C      8        C           7

我想从名称中删除标志,然后以某种方式使用groupby或merge,但没有达到预期效果。

groupby
with
shift

df['related id']=df.groupby(df.name.str.split().str[0]).id.shift()
df
Out[11]: 
      name  id flag  related id
0  test1 A   1    A         NaN
1  test1 B   2    B         1.0
2  test2 A   3    A         NaN
3  test2 B   4    B         3.0
4    test3   5    0         NaN
5  test4 A   6    A         NaN
6  test4 B   7    B         6.0
7  test4 C   8    C         7.0

groupby
with
shift

df['related id']=df.groupby(df.name.str.split().str[0]).id.shift()
df
Out[11]: 
      name  id flag  related id
0  test1 A   1    A         NaN
1  test1 B   2    B         1.0
2  test2 A   3    A         NaN
3  test2 B   4    B         3.0
4    test3   5    0         NaN
5  test4 A   6    A         NaN
6  test4 B   7    B         6.0
7  test4 C   8    C         7.0

这看起来不错!所以我假设数据帧必须按名称排序,因为我们只是在移动索引?或者groupby是如何处理的?这看起来不错!所以我假设数据帧必须按名称排序,因为我们只是在移动索引?或者groupby是如何处理的?