Home > Backend Development > Python Tutorial > How to Calculate the Cartesian Product of Two Pandas DataFrames?

How to Calculate the Cartesian Product of Two Pandas DataFrames?

Barbara Streisand
Release: 2024-12-09 06:37:09
Original
539 people have browsed it

How to Calculate the Cartesian Product of Two Pandas DataFrames?

Cartesian Product in Pandas

Problem:

Obtain the Cartesian product of two Pandas dataframes without explicitly defining it.

Example:

import pandas as pd

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

Desired output:

   col1  col2  col3
0     1     3     5
1     1     3     6
2     2     4     5
3     2     4     6
Copy after login

Solution:

For Pandas >= 1.2:

Using the built-in merge function:

df1.merge(df2, how='cross')
Copy after login

For Pandas < 1.2:

Using merge with a repeated key:

key_df = pd.DataFrame({'key': [1, 1], 'col1': [1, 2], 'col2': [3, 4]})
merge(key_df, df2, on='key')[['col1', 'col2', 'col3']]
Copy after login

The above is the detailed content of How to Calculate the Cartesian Product of Two Pandas DataFrames?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template