大熊猫数据框的笛卡尔积与自身

cs9*_*s95 4 python dataframe pandas

给定一个数据帧:

    id  value
0    1     a
1    2     b
2    3     c
Run Code Online (Sandbox Code Playgroud)

我想获得一个新的数据帧,它基本上是每行的笛卡尔积,每行不包括自身:

    id  value id_2 value_2
0    1     a     2    b
1    1     a     3    c
2    2     b     1    a
3    2     b     3    c
4    3     c     1    a
5    3     c     2    b
Run Code Online (Sandbox Code Playgroud)

这是我现在的做法.我使用itertools获取产品,然后使用pd.concatwith df.loc来获取新的数据帧.

from itertools import product

ids = df.index.values
ids_1, ids_2 = list(zip(*filter(lambda x: x[0] != x[1], product(ids, ids))))

df_new = pd.concat([df.loc[ids_1, :].reset_index(), df.loc[ids_2, :].reset_index()], 1).drop('index', 1)

df_new

   id value  id value
0   1     a   2     b
1   1     a   3     c
2   2     b   1     a
3   2     b   3     c
4   3     c   1     a
5   3     c   2     b
Run Code Online (Sandbox Code Playgroud)

有更简单的方法吗?

piR*_*red 6

我们想得到方形矩阵的上三角和下三角的索引.或者换句话说,单位矩阵为零

np.eye(len(df))

array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
Run Code Online (Sandbox Code Playgroud)

所以我从1减去它

array([[ 0.,  1.,  1.],
       [ 1.,  0.,  1.],
       [ 1.,  1.,  0.]])
Run Code Online (Sandbox Code Playgroud)

在布尔上下文中传递给np.where我,我得到的正上下三角形索引.

i, j = np.where(1 - np.eye(len(df)))
df.iloc[i].reset_index(drop=True).join(
    df.iloc[j].reset_index(drop=True), rsuffix='_2')

   id value  id_2 value_2
0   1     a     2       b
1   1     a     3       c
2   2     b     1       a
3   2     b     3       c
4   3     c     1       a
5   3     c     2       b
Run Code Online (Sandbox Code Playgroud)