Monday, September 1, 2025
HomeLanguagesPandas – All combinations of two columns

Pandas – All combinations of two columns

In this article, we will see how to get the combination of two columns of a DataFrame. First, let’s create a sample DataFrame.

Code: An example code to create a data frame using dictionary.

Python3




# importing pandas module for the  
# data frame
import pandas as pd
  
# creating data frame for student details 
# using dictionary
data = pd.DataFrame({'id': [7058, 7059, ], 
                     'name': ['sravan', 'jyothika']})
  
print(data)


Output:

To combine two columns in a data frame using itertools module. It provides various functions that work on iterators to produce complex iterators. To get all combinations of columns we will be using itertools.product module. This function computes the cartesian product of input iterables. To compute the product of an iterable with itself, we use the optional repeat keyword argument to specify the number of repetitions. The output of this function is tuples in sorted order.

Syntax: itertools.product(iterables, repeat=1)

Code:

Python3




# import pandas as pd
import pandas as pd
  
# creating data frame
df = pd.DataFrame(data=[['sravan', 'Sudheer'], 
                        ['radha', 'vani'], ],
                  columns=['gents', 'ladies'])
  
print(df)


Output:

Code:

Python3




# importing product
from itertools import product
  
# apply product method
print(list(product(df['gents'], df['ladies'])))


Output:

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32251 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6619 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11841 POSTS0 COMMENTS
Shaida Kate Naidoo
6735 POSTS0 COMMENTS
Ted Musemwa
7016 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6707 POSTS0 COMMENTS