While working with data in Pandas in Python, we perform a vast array of operations on the data to get the data in the desired form. One of these operations could be that we want to remap the values of a specific column in the DataFrame. Let’s discuss several ways in which we can do that.
Creating Pandas DataFrame to remap values
Given a Dataframe containing data about an event, remap the values of a specific column to a new value.
Python3
import pandas as pd
df = pd.DataFrame({ 'Date' : [ '10/2/2011' , '11/2/2011' , '12/2/2011' , '13/2/2011' ],
'Event' : [ 'Music' , 'Poetry' , 'Theatre' , 'Comedy' ],
'Cost' : [ 10000 , 5000 , 15000 , 2000 ]})
print (df)
|
Output:
Remap values in Pandas columns using replace() function
Now we will remap the values of the ‘Event’ column by their respective codes using replace() function.
Python3
dict = { 'Music' : 'M' , 'Poetry' : 'P' , 'Theatre' : 'T' , 'Comedy' : 'C' }
print ( dict )
df.replace({ "Event" : dict })
|
Output :
Remap values in Pandas DataFrame columns using map() function
Now we will remap the values of the ‘Event’ column by their respective codes using map() function.
Python3
dict = { 'Music' : 'M' , 'Poetry' : 'P' , 'Theatre' : 'T' , 'Comedy' : 'C' }
print ( dict )
df[ 'Event' ] = df[ 'Event' ]. map ( dict )
print (df)
|
Output:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
27 Sep, 2022
Like Article
Save Article