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 - Return a new Index of the values set with the mask
To return a new Index of the values set with the mask, use the index.putmask() method in Pandas. This method creates a new Index where values meeting a specified condition are replaced with a new value.
Syntax
Index.putmask(mask, value)
Parameters
The putmask() method accepts the following parameters:
- mask ? A boolean condition that determines which values to replace
- value ? The replacement value for positions where mask is True
Example
Let's create a Pandas Index and demonstrate how putmask() works ?
import pandas as pd
# Creating Pandas index
index = pd.Index([5, 65, 10, 17, 75, 40])
# Display the Pandas index
print("Original Index:")
print(index)
# Display index properties
print("\nNumber of elements:", index.size)
print("Data type:", index.dtype)
# Replace values less than 30 with 111
new_index = index.putmask(index < 30, 111)
print("\nAfter putmask (values < 30 replaced with 111):")
print(new_index)
Original Index: Index([5, 65, 10, 17, 75, 40], dtype='int64') Number of elements: 6 Data type: int64 After putmask (values < 30 replaced with 111): Index([111, 65, 111, 111, 75, 40], dtype='int64')
Multiple Conditions Example
You can also use more complex boolean conditions with putmask() ?
import pandas as pd
# Create index with different values
index = pd.Index([1, 25, 50, 75, 100, 125])
print("Original Index:")
print(index)
# Replace values between 20 and 80 with -1
mask = (index >= 20) & (index <= 80)
new_index = index.putmask(mask, -1)
print("\nAfter putmask (values between 20-80 replaced with -1):")
print(new_index)
Original Index: Index([1, 25, 50, 75, 100, 125], dtype='int64') After putmask (values between 20-80 replaced with -1): Index([1, -1, -1, -1, 100, 125], dtype='int64')
Key Points
-
putmask()returns a new Index without modifying the original - The mask parameter must be a boolean array or condition
- All values where mask is True get replaced with the specified value
- The returned Index maintains the same dtype as the original
Conclusion
The putmask() method provides an efficient way to conditionally replace values in a Pandas Index. Use it when you need to create a new Index with specific values replaced based on boolean conditions.
Advertisements
