pandas 数据框的笛卡尔积与自身 [英] Cartesian product of a pandas dataframe with itself

查看:58
本文介绍了 pandas 数据框的笛卡尔积与自身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个数据框:

    id  value
0    1     a
1    2     b
2    3     c

我想获得一个新的数据框,该数据框基本上是每一行与彼此不包含其自身的另一行的笛卡尔乘积:

I want to get a new dataframe that is basically the cartesian product of each row with each other row excluding itself:

    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

这是我目前的做法.我使用itertools来获取产品,然后将pd.concatdf.loc一起使用以获取新的数据框.

This is my approach as of now. I use itertools to get the product and then use pd.concat with df.loc to get the new dataframe.

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

有没有更简单的方法?

推荐答案

我们要获取方矩阵的上,下三角形的索引.换句话说,单位矩阵为零

We want to get the indices for the upper and lower triangles of a square matrix. Or in other words, where the identity matrix is zero

np.eye(len(df))

array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

所以我从1减去

array([[ 0.,  1.,  1.],
       [ 1.,  0.,  1.],
       [ 1.,  1.,  0.]])

在布尔值上下文中并传递给np.where,我恰好获得了上,下三角形索引.

In a boolean context and passed to np.where I get exactly the upper and lower triangle indices.

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

这篇关于 pandas 数据框的笛卡尔积与自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆