首页 >后端开发 >Python教程 >如何计算两个 Pandas DataFrame 的笛卡尔积?

如何计算两个 Pandas DataFrame 的笛卡尔积?

Barbara Streisand
Barbara Streisand原创
2024-12-09 06:37:09578浏览

How to Calculate the Cartesian Product of Two Pandas DataFrames?

Pandas 中的笛卡尔积

问题:

在没有明确定义的情况下获取两个 Pandas 数据帧的笛卡尔积

示例:

import pandas as pd

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

所需输出:

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

解决方案:

对于熊猫>= 1.2:

使用内置合并功能:

df1.merge(df2, how='cross')

对于 Pandas

对于 Pandas
key_df = pd.DataFrame({'key': [1, 1], 'col1': [1, 2], 'col2': [3, 4]})
merge(key_df, df2, on='key')[['col1', 'col2', 'col3']]
1.2:使用带有重复键的合并:

以上是如何计算两个 Pandas DataFrame 的笛卡尔积?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn