Replace Values in Pandas Dataframe Examples
Here, we are going to see the implementation of dataframe.replace() methods with the help of some examples. For a link to the CSV file Used in Code, click here
Python3
# importing pandas as pd import pandas as pd # Making data frame from the csv file df = pd.read_csv( "nba.csv" ) # Printing the first 10 rows of the data frame for visualization df[: 10 ] |
Output:
Example 1: Replacing a Single Value
We are going to replace team “Boston Celtics” with “Omega Warrior” in the ‘df’ Dataframe.
Python3
# this will replace "Boston Celtics" with "Omega Warrior" df.replace(to_replace = "Boston Celtics" , value = "Omega Warrior" ) |
Output:
Example 2: Replacing Two Values with a Single Value
Replacing more than one value at a time. Using python list as an argument We are going to replace team “Boston Celtics” and “Texas” with “Omega Warrior” in the ‘df’ Dataframe.
Python3
# importing pandas as pd import pandas as pd # Making data frame from the csv file df = pd.read_csv( "nba.csv" ) # this will replace "Boston Celtics" and "Texas" with "Omega Warrior" df.replace(to_replace = [ "Boston Celtics" , "Texas" ], value = "Omega Warrior" ) |
Output:
Notice the College column in the first row, “Texas” has been replaced with “Omega Warriors”
Example 3: Replacing Nan With a Random Integer Value
Replace the Nan value in the data frame with the -99999 value.
Python3
# importing pandas as pd import pandas as pd # Making data frame from the csv file df = pd.read_csv( "nba.csv" ) # will replace Nan value in dataframe with value -99999 df.replace(to_replace = np.nan, value = - 99999 ) |
Output
Notice all the Nan value in the data frame has been replaced by -99999. Though for practical purposes we should be careful with what value we are replacing nan value.
Example 4: Replacing With Multiple Values
In this example, we are replacing multiple values in a Pandas Dataframe by using dataframe.replace() function.
Python3
# importing pandas as pd import pandas as pd # Making data frame from the csv file df = pd.read_csv( "nba.csv" ) df1 = df.replace([ 'Boston Celtics' , 'Amir Johnson' , 'R.J. Hunter' ], [ 'Omega Warriors' , 'Mitcell Johnson' , 'Shivang Thomas' ]) df1[: 10 ] |
Output
Python | Pandas dataframe.replace()
Pandas dataframe.replace() function is used to replace a string, regex, list, dictionary, series, number, etc. from a Pandas Dataframe in Python. Every instance of the provided value is replaced after a thorough search of the full DataFrame.
Contact Us