Python Pandas - Compute the symmetric difference of two Index objects

To compute the symmetric difference of two Index objects, use the index1.symmetric_difference(index2) method in Pandas. The symmetric difference returns elements that are in either index but not in both.

What is Symmetric Difference?

The symmetric difference of two sets contains elements that are present in either set but not in their intersection. For Index objects, this means finding values that exist in only one of the two indexes.

Syntax

index1.symmetric_difference(index2)

Parameters

  • other: Another Index object to compute symmetric difference with
  • sort: Boolean, whether to sort the result (default: None)

Example

Let's create two Index objects and find their symmetric difference ?

import pandas as pd

# Creating two Pandas index
index1 = pd.Index([10, 20, 30, 40, 50])
index2 = pd.Index([40, 10, 60, 20, 55])

# Display the Pandas indexes
print("Pandas Index1...\n", index1)
print("Pandas Index2...\n", index2)

# Return the number of elements in each index
print("\nNumber of elements in index1...\n", index1.size)
print("\nNumber of elements in index2...\n", index2.size)

# Perform symmetric difference
res = index1.symmetric_difference(index2)

# Display the symmetric difference result
print("\nThe index1 and index2 symmetric difference...\n", res)
Pandas Index1...
 Index([10, 20, 30, 40, 50], dtype='int64')
Pandas Index2...
 Index([40, 10, 60, 20, 55], dtype='int64')

Number of elements in index1...
5

Number of elements in index2...
5

The index1 and index2 symmetric difference...
Index([30, 50, 55, 60], dtype='int64')

How It Works

In the example above:

  • Index1 contains: [10, 20, 30, 40, 50]
  • Index2 contains: [40, 10, 60, 20, 55]
  • Common elements: [10, 20, 40]
  • Elements only in Index1: [30, 50]
  • Elements only in Index2: [55, 60]
  • Symmetric difference: [30, 50, 55, 60]

Conclusion

The symmetric_difference() method efficiently finds elements that exist in either index but not in both. This is useful for identifying unique values when comparing datasets or indexes.

Updated on: 2026-03-26T16:30:06+05:30

564 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements