+

Python | Pandas Index.union ()

Index.union() Pandas Index.union() joins two Index objects and sorts them , if possible. The following function behaves like a standard set union operation. The function can also find a union of categorical data.

Syntax: Index.union (other)

Parameters:
other: Index or array-like

Returns: union: Index

Example # 1: Use Index.union () to find the union of two indexes.

# import pandas as pd

import pandas as pd

 
# Create first index

idx1 = pd.Index ([ 10 , 20 , 18 , 32 ])

 
# Create second index

idx2 = pd.Index ([ 21 , 10 , 30 , 40 , 50 ])

 
# Print first index

print (idx1)

 
# Print the second index

print ( "" , idx2)

Exit :

Let`s find the union of these two indices

# merge the two indices
idx1.union (idx2)

Output:

The function found the concatenation of these two indices.

Example # 2: Use Index.union () to perform a set join operation on the data of two indexes. Index marks are of string type.

# import pandas as pd

import pandas as pd

 
# Create first index

idx1 = pd .Index ([ `Harry` , ` Mike` , `Arther` , `Nick` ],

  name = `Student` )

 
# Create second index

idx2 = pd.Index ([ `Alice` , ` Bob` , `Rachel` , ` Tyler` , `Louis` ],

name = `Winners` )

  
# Print first index

print (idx1)

 
# Print second index

print ( " " , idx2)

Output:

Let`s find the union of these two indexes.

# find the union of two indices
idx1.union (idx2)

Output:

The function returned a new index that contains the result of the union of the idx1 and idx2 sets.

Get Solution for free from DataCamp guru