sql - Pandas 中的复杂连接

标签 sql join merge pandas

你怎么能用 Pandas 写这个?使用 SQL 更好吗?

我尝试过“where”、“isin”、“join”、“merge”,但无法在 Pandas 中复制它。

问题:
我基本上有两列(x 和 y),其值从 1 到 10。然后我想使用如下所示的特定条件进行自连接。

IF OBJECT_ID('tempdb..#t1','u') IS NOT NULL
BEGIN
DROP TABLE #t1
END

    CREATE TABLE #t1
    (
        x int,
        y int
    )

INSERT #t1
select distinct number as x, number as y from Master..spt_values
where number between 1 and 10
order by number

select a.x as a_x,
        a.y as a_y,
        b.x as b_x,
        b.y as b_y
from #t1 as a
join #t1 as b on (a.x <= b.x and a.x > b.x-4)
order by a.x,a.y

有什么建议吗?

以下是没有 SQL 的查询结果:

a_x a_y b_x b_y
1 1 1 1
1 1 2 2
1 1 3 3
1 1 4 4
2 2 2 2
2 2 3 3
2 2 4 4
2 2 5 5
3 3 3 3
3 3 4 4
3 3 5 5
3 3 6 6
4 4 4 4
4 4 5 5
4 4 6 6
4 4 7 7
5 5 5 5
5 5 6 6
5 5 7 7
5 5 8 8
6 6 6 6
6 6 7 7
6 6 8 8
6 6 9 9
7 7 7 7
7 7 8 8
7 7 9 9
7 7 10 10
8 8 8 8
8 8 9 9
8 8 10 10
9 9 9 9
9 9 10 10
10 10 10 10

这是数据框

df = pd.DataFrame({'x':range(1,11),
                   'y':range(1,11)})

最佳答案

这是一个解决方案:

import pandas as pd
import numpy as np
df = pd.DataFrame({'x':range(1,11),
                   'y':range(1,11)})
df2 = pd.merge(df, df, on=np.ones(df.shape[0]), suffixes=("_a", "_b")).drop("key_0", axis=1)
print df2.query("x_a <= x_b & x_a > x_b - 4").reset_index(drop=True)

输出是:

    x_a  y_a  x_b  y_b
0     1    1    1    1
1     1    1    2    2
2     1    1    3    3
3     1    1    4    4
4     2    2    2    2
5     2    2    3    3
6     2    2    4    4
7     2    2    5    5
8     3    3    3    3
9     3    3    4    4
10    3    3    5    5
11    3    3    6    6
12    4    4    4    4
13    4    4    5    5
14    4    4    6    6
15    4    4    7    7
16    5    5    5    5
17    5    5    6    6
18    5    5    7    7
19    5    5    8    8
20    6    6    6    6
21    6    6    7    7
22    6    6    8    8
23    6    6    9    9
24    7    7    7    7
25    7    7    8    8
26    7    7    9    9
27    7    7   10   10
28    8    8    8    8
29    8    8    9    9
30    8    8   10   10
31    9    9    9    9
32    9    9   10   10
33   10   10   10   10

关于sql - Pandas 中的复杂连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22723286/

相关文章:

SQL ANY 查询 - 语法有效

batch-file - 合并不带标题的 CSV 文件

r - 使用 R 中第二个数据表中的观测值填充一个数据表中的 NA 值

mysql - 来自 2 个表中的 GROUP BY 和 COUNT 的 SQL 连接结果

mysql - 何时在 MySQL 中使用单引号、双引号和反引号

SQL 条件求和

join - 参加弹性搜寻

php - 基于连接查询记录未返回预期结果

mysql - 需要一个查询将某些 mySQL 数据库列放入一行

ruby - NoMethodError : undefined method `reverse_merge'