Have you ever tried to change multiple values in a dataframe at once? We can do this very easily by replacing the values with another using a simple python code.
So this recipe is a short example on how to replace multiple values in a dataframe. Let's get started.
import pandas as pd
import numpy as np
Here we have imported Pandas and Numpy which are very general libraries.
Let us create a simple dataset and convert it to a dataframe. This is a dataset of city with different features in it like City_level, City_pool, Rating, City_port and City_Temperature. We have converted this dataset into a dataframe with its features as columns.
city_data = {'city_level': [1, 3, 1, 2, 2, 3, 1, 1, 2, 3],
'city_pool' : ['y','y','n','y','n','n','y','n','n','y'],
'Rating': [1, 5, 3, 4, 1, 2, 3, 5, 3, 4],
'City_port': [0, 1, 0, 1, 0, 0, 1, 1, 0, 1],
'city_temperature': ['low', 'medium', 'medium', 'high', 'low','low', 'medium', 'medium', 'high', 'low']}
df = pd.DataFrame(city_data, columns = ['city_level', 'city_pool', 'Rating', 'City_port', 'city_temperature'])
So let us consider that first we want to print the initial dataset and then we want to replace digit 1 (where ever it is present in the dataset) with the string 'one'. Finally we want to view the new dataset with the changes.
So for this we have to use replace function which have 3 important parameters in it.
print(df)
df = df.replace(1, 'One')
print(); print(df)
Once we run the above code snippet, we will see that the all the 1s in the dataset will be changed to 'one'.
city_level city_pool Rating City_port city_temperature 0 1 y 1 0 low 1 3 y 5 1 medium 2 1 n 3 0 medium 3 2 y 4 1 high 4 2 n 1 0 low 5 3 n 2 0 low 6 1 y 3 1 medium 7 1 n 5 1 medium 8 2 n 3 0 high 9 3 y 4 1 low city_level city_pool Rating City_port city_temperature 0 One y One 0 low 1 3 y 5 One medium 2 One n 3 0 medium 3 2 y 4 One high 4 2 n One 0 low 5 3 n 2 0 low 6 One y 3 One medium 7 One n 5 One medium 8 2 n 3 0 high 9 3 y 4 One low