Pandas: 多条件交叉连接

Pandas: cross join with multiple conditions

考虑以下查询:

SELECT *
    FROM
      table_1
    CROSS JOIN
      table_2
    WHERE
      table_1.f1 >= table_2.f1001 
      AND (
        table_1.f1 < table_2.f1002
        OR table_2.f1002 IS NULL
      )

是否可以使用 Pandas 来实现,例如 pd.merge(how='cross')?假设我们有两个数据帧table_1table_1,我们需要根据以下条件进行交叉连接:

table_1.f1 >= table_2.f1001 AND (table_1.f1 < table_2.f1002 OR table_2.f1002 IS NULL)

你可以这样做

out = pd.merge(table_1, table_2,how='cross')
out = out[out['f1'].ge(out['f1001']) & (out['f1'].lt(out['f1001']) | table_2['f1002'].isna())]

使用mergequery:

out = pd.merge(table_1, table_2, how='cross') \
        .query("(f1 >= f1001) & ((f1 < f1002) | f1002.isna())")
df.merge(df, on='cid', suffixes=('1','2')).query('qid1 < qid2')

类似的东西,在 merge

之后使用 query