📜  Python| Pandas Index.difference()(1)

📅  最后修改于: 2023-12-03 15:04:21.760000             🧑  作者: Mango

Python | Pandas Index.difference()

The Index.difference() method in Pandas is used to return the values in the given index that are NOT in the other provided index. It returns a new Index that contains the unique values.

Syntax
Index.difference(other, sort=False)
  • other: The other Index or iterable to compare with the original index.
  • sort (optional): Whether to sort the resulting Index. Default is False.
Parameters
  • other: It can be a list, tuple, or another Index object to compare with the original index.
  • sort: If set to True, the resulting Index will be sorted lexically. If set to False, the order will be the same as the original Index.
Returns

This method returns a new Index containing the values that are present in the original Index but not in the other provided index.

Example
import pandas as pd

index1 = pd.Index([1, 2, 3, 4, 5])
index2 = pd.Index([3, 4, 5, 6, 7])

difference = index1.difference(index2)
print(difference)

Output:

Int64Index([1, 2], dtype='int64')

In the above example, the difference between index1 and index2 is calculated using the difference() method. It returns an Int64Index containing the values [1, 2], which are present in index1 but not in index2.

Conclusion

The Index.difference() method in Pandas is a useful method to find the unique values in one index that are not present in another index. It provides a simple way to compare and find the differences between two indices.