我正在尝试将每一行与其他每一行进行比较。我不想使用apply,因为我以后需要能够使用结果并且应用花费太长时间。目前,使用MySQL进行此过程不到一秒钟,并且希望在熊猫中花费相同的时间。
开头的表格。
import pandas
columns = ["id", "c1", "c2", "c3", "c4"]
table = [
[1, 'test', 'a1', 100, "unspecified"],
[2, 'test', 'a2', 200, "unspecified"],
[3, 'test', 'a3', 300, "unspecified"],
]
df = pandas.DataFrame(data=table, columns=columns)
在MySQL中查询
SELECT *
FROM
db.df AS s1,
db.df AS s2;
由于此查询,最终得到的结果是,我希望得到相同的结果,但只使用pandas或至少在python中使用
。id c1 c2 c3 c4 id c1 c2 c3 c4
1 test a1 100 unspecified 1 test a1 100 unspecified
2 test a2 200 unspecified 1 test a1 100 unspecified
3 test a1 300 unspecified 1 test a1 100 unspecified
1 test a1 100 unspecified 2 test a2 200 unspecified
2 test a2 200 unspecified 2 test a2 200 unspecified
3 test a1 300 unspecified 2 test a2 200 unspecified
1 test a1 100 unspecified 3 test a1 300 unspecified
2 test a2 200 unspecified 3 test a1 300 unspecified
3 test a1 300 unspecified 3 test a1 300 unspecified
如您所见,所有行都相互比较。我是熊猫的新手,在看文档时,我似乎找不到任何可以帮助我实现这一目标的东西。当前,我通过在docker容器中启动MySQL数据库并在该容器上运行该进程来解决此问题,但这似乎是一种漫长的过程,这给自动测试带来了麻烦。那么有没有一种方法可以在大熊猫中获得相同的结果
答案 0 :(得分:0)
由于您的MySQL查询是CROSS JOIN
的隐式旧版本,因此通过合并具有相同值的键在熊猫中运行相同的笛卡尔叉积:
cj_df = pd.merge(df.assign(key = 1), df.assign(key = 1), on = 'key')
并使用id
字段添加一个过滤器以避免反向重复和同一行匹配:
cj_df = (pd.merge(df.assign(key = 1), df.assign(key = 1), on = 'key')
.query("id_x < id_y")
.drop(columns = ['key'])
)