Pandas 数据帧 - "成对"连接作为基于唯一 id 的新列



我有一个数据框,如下所示:

        id  name
    0   12  molly
    1   12  james
    2   10  adam
    3   8   susan
    4   10  molly
    5   9   pete
    6   2   james
    7   10  Bob
    8   8   james
    9   2   adam
    10  12  Gary

我想根据带有 cols "name_x"和"name_y"的 id 号创建"成对"列,其中两个名称具有相同的 id,如下所示:

    id  name_x  name_y
0   12  molly   james
1   12  molly   gary
2   12  gary    james
3   10  adam    molly
4   10  adam    Bob
5   10  molly   Bob
6   8   susan   james
7   2   james   adam

我知道一定在某个地方有一个解决方案,但我想不出正确的术语来找到它!

让我们使用 itertools.combiniations:

from itertools import combinations
df.groupby('id')['name']
  .apply(lambda x: pd.DataFrame((i for i in combinations(x.values,2))))
  .reset_index().drop('level_1',axis=1)
  .rename(columns={0:'name_x',1:'name_y'})

输出:

   id name_x name_y
0   2  james   adam
1   8  susan  james
2  10   adam  molly
3  10   adam    Bob
4  10  molly    Bob
5  12  molly  james
6  12  molly   Gary
7  12  james   Gary

itertools.combinations的另一个选项如下:

In [30]: from itertools import combinations
In [31]: df.groupby('id').name.apply(lambda group: list(combinations(group, 2))).apply(pd.Series).stack().reset_index(level=1, drop=True).apply(pd.Series).rename(columns={0: 'name_x', 1: 'name_y'})
Out[31]:
   name_x name_y
id
2   james   adam
8   susan  james
10   adam  molly
10   adam    Bob
10  molly    Bob
12  molly  james
12  molly   Gary
12  james   Gary

最新更新