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 - Replace index values where the condition is False
To replace index values where the condition is False, use the where() method combined with isin() in Pandas. This allows you to conditionally replace index values based on whether they meet specific criteria.
Syntax
index.where(condition, other)
Parameters:
-
condition? Boolean condition to evaluate -
other? Value to use where condition is False
Creating a Pandas Index
First, let's create a Pandas index with product categories ?
import pandas as pd
# Creating Pandas index
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')
print("Original Pandas Index:")
print(index)
Original Pandas Index: Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')
Replace Values Using where() and isin()
Now let's replace all values except 'Decor' with 'Miscellaneous' using the where() method ?
import pandas as pd
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')
# Replace values where condition is False
# Only 'Decor' satisfies the condition, others get replaced
result = index.where(index.isin(['Decor']), 'Miscellaneous')
print("After replacement:")
print(result)
After replacement: Index(['Miscellaneous', 'Miscellaneous', 'Decor', 'Miscellaneous', 'Miscellaneous'], dtype='object', name='Products')
Multiple Values Example
You can also keep multiple values and replace the rest ?
import pandas as pd
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')
# Keep 'Electronics' and 'Books', replace others
result = index.where(index.isin(['Electronics', 'Books']), 'Other')
print("Keeping Electronics and Books:")
print(result)
Keeping Electronics and Books: Index(['Electronics', 'Other', 'Other', 'Books', 'Other'], dtype='object', name='Products')
How It Works
The where() method works as follows:
-
index.isin(['Decor'])returns a boolean array - Where the condition is
True, original values are kept - Where the condition is
False, values are replaced with the specified replacement
Conclusion
Use index.where() combined with isin() to conditionally replace index values. This method preserves values that match your criteria while replacing all others with a specified value.
Advertisements
