Pandas相当于SQL CROSS JOIN(笛卡尔积)

Bro*_*try 7 python sql join pandas

假设我有两张桌子:

表格1:

   col1  col2
      0     1
      2     3
Run Code Online (Sandbox Code Playgroud)

表2:

   col3  col4
      5     6
      7     8
Run Code Online (Sandbox Code Playgroud)

在SQL中,如果我发出以下声明:

Select *
From Table1, Table2;
Run Code Online (Sandbox Code Playgroud)

我期望从两个表中获得包含所有组合的表格:

col1 col2 col3 col4
   0    1    5    6
   0    1    7    8
   2    3    5    6
   2    3    7    8
Run Code Online (Sandbox Code Playgroud)

有没有办法在pandas中使用两个数据帧做同样的事情?

cs9*_*s95 13

标准习语是merge在虚拟列上使用.

df1.assign(foo=1).merge(df2.assign(foo=1)).drop('foo', 1)

   col1  col2  col3  col4
0     0     1     5     6
1     0     1     7     8
2     2     3     5     6
3     2     3     7     8
Run Code Online (Sandbox Code Playgroud)

  • @samutamm 仅当 DataFrame 中的非键列共享相同名称时才需要。 (2认同)