Python-Pandas的笛卡尔积

发布于 2021-02-02 23:21:24

我有两个pandas数据框:

from pandas import DataFrame
df1 = DataFrame({'col1':[1,2],'col2':[3,4]})
df2 = DataFrame({'col3':[5,6]})

获得其笛卡尔积的最佳实践是什么(当然不用像我这样明确地编写它)?

#df1, df2 cartesian product
df_cartesian = DataFrame({'col1':[1,2,1,2],'col2':[3,4,3,4],'col3':[5,5,6,6]})
关注者
0
被浏览
305
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    如果每行都有一个重复的键,则可以使用merge生成笛卡尔乘积(就像在SQL中一样)。

    from pandas import DataFrame, merge
    df1 = DataFrame({'key':[1,1], 'col1':[1,2],'col2':[3,4]})
    df2 = DataFrame({'key':[1,1], 'col3':[5,6]})
    
    merge(df1, df2,on='key')[['col1', 'col2', 'col3']]
    

    输出:

       col1  col2  col3
    0     1     3     5
    1     1     3     6
    2     2     4     5
    3     2     4     6
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看