Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Compute indexer and mask for new index given the current index
To compute indexer and mask for new index given the current index, use the get_indexer() method in Pandas. This method returns an array of indices corresponding to the positions of the target elements in the original index.
Syntax
Index.get_indexer(target, method=None, limit=None, tolerance=None)
Parameters
The key parameters are ?
- target ? The target values to find indices for
- method ? Method to use for inexact matches (pad, backfill, nearest)
- limit ? Maximum number of consecutive NaN values to forward/backward fill
- tolerance ? Maximum distance between original and target values
Example
Let's create a Pandas index and compute indexer positions for target values ?
import pandas as pd
# Creating Pandas index
index = pd.Index([10, 20, 30, 40, 50, 60, 70])
# Display the Pandas index
print("Pandas Index...\n", index)
# Return the number of elements in the index
print("\nNumber of elements in the index...\n", index.size)
# Compute indexer and mask
# Marked by -1, as it is not in index
print("\nGet the indexes...\n", index.get_indexer([30, 40, 90, 100, 50]))
Pandas Index... Int64Index([10, 20, 30, 40, 50, 60, 70], dtype='int64') Number of elements in the index... 7 Get the indexes... [ 2 3 -1 -1 4]
How It Works
The get_indexer() method returns an array where ?
- Positive integers represent the position of found elements
-
-1indicates elements not found in the original index - For target
[30, 40, 90, 100, 50], the result is[2, 3, -1, -1, 4]
Using Different Methods
You can use different methods for handling missing values ?
import pandas as pd
index = pd.Index([10, 20, 30, 40, 50])
target = [15, 25, 35, 45]
print("Exact match (default):")
print(index.get_indexer(target))
print("\nUsing 'pad' method (forward fill):")
print(index.get_indexer(target, method='pad'))
print("\nUsing 'backfill' method:")
print(index.get_indexer(target, method='backfill'))
Exact match (default): [-1 -1 -1 -1] Using 'pad' method (forward fill): [0 1 2 3] Using 'backfill' method: [1 2 3 4]
Conclusion
The get_indexer() method efficiently finds positions of target values in a Pandas index. Use different methods like 'pad' or 'backfill' for approximate matching when exact matches are not found.
Advertisements
