pandas 将两列合并为一个“集合”

Noa*_*kel 1 python pandas

我试图在 pandas 中找到一种简单的方法来合并行,其中我们将一组列视为集合。例如A、B是一个集合。

  A B C
0 a b 1
1 b a 3
2 c c 1
3 d a 5
Run Code Online (Sandbox Code Playgroud)

所以我想合并=[A,B] 给我:

  A B C1 C2
0 a b 1  3
2 c c 1  Nan
3 d a 5  Nan
Run Code Online (Sandbox Code Playgroud)

raf*_*elc 5

IIUC,你可以使用

np.sort+groupby

d = pd.DataFrame(np.sort(df[['A', 'B']].values,1))
     
df.groupby((d!=d.shift()).cumsum().sum(1)).C.agg(list).apply(pd.Series)

    0   1
2   1.0 3.0
4   1.0 NaN
6   5.0 NaN
Run Code Online (Sandbox Code Playgroud)

或者

frozenset+apply

df.groupby(df[['A', 'B']].apply(frozenset,1)).C.agg(list).apply(pd.Series)


        0   1
(a, b)  1.0 3.0
(c)     1.0 NaN
(a, d)  5.0 NaN
Run Code Online (Sandbox Code Playgroud)