Overview:
-
The DataFrame class of pandas library provides several means to replace one or more elements of a DataFrame. They include loc, iloc properties of the DataFrame and the methods mask() and replace().
-
Together all these methods facilitate replacement of one or more elements based on labels, indexes, boolean expressions, regular expressions and through explicit specification of values.
-
Using the mask() method, the elements of a pandas DataFrame can be replaced with the value from an another DataFrame using a Boolean condition or a function returning the replacement value.
-
By default, the mask() method uses a default DataFrame whose elements are all NaN as the source of replacement values. For example, any entry present in a DataFrame that is greater than the integer value 10 can be replaced with some other value as defined by another DataFrame or a function.
Example 1 - Replacing the elements with the values from the another(the default) DataFrame :
# Example Python program that replaces a DataFrame elements using a # Boolean condition. The replacement values come from the default # DataFrame used by the mask() method which has all NaN values. import pandas as pds # Python dictionary of hourly readings # Replace values matching a threshold |
Output:
Original DataFrame: |
Example 2 - Replacing the elements with the values from an another DataFrame :
# Example Python program that replaces element values of a DataFrame # Create the DataFrame whose values print("DataFrame:"); # DataFrame that supplies replacement values repValues = pds.DataFrame(data=frame2); # Replace values using a Boolean expression |
Output:
DataFrame: |
Example 3 - Explicitly replacing a set of values through the replace() method:
# Example Python program that replaces # Create a DataFrame df = pds.DataFrame(data=matrix1); # Replace row1 with all zeros |
Output:
DataFrame: 0 1 2 0 1 2 3 1 4 5 6 2 7 8 9 DataFrame after replacing the first row of values: 0 1 2 0 0 0 0 1 4 5 6 2 7 8 9 |
Example 4 - Replacing the string elements of a DataFrame using a regular expression:
# Example Python program that uses a regular expression tokens = [("The", "quick", "brown"), # Replace lower cases of "t" or "h" or "e" with an "a" |
Output:
DataFrame with string literals: |
Example 5 - Replacing an element of a DataFrame using labels:
# Example Python program that replaces import pandas as pds # A list of tuples # Create a DataFrame print("DataFrame after replacing a value through labels:"); |
Output:
DataFrame: |
Example 6 - Replacing an element of a DataFrame using its indices:
# Example Python program that replaces import pandas as pds # A list of tuples # DataFrame creation print("DataFrame after replacing a value through its indices:"); |
Output:
DataFrame: |