0

I have the following data frame.

col1 col2 col3
1    1    1
2    2    2
3    1    2
3    3    3

I want to replace numerical values based on the following mappings

col1: {1: dog, 2: cat, 3: bird}
col2: {1: yellow, 2: orange, 3: red}
col3: {1: dave, 2: pete, 3: tom}

How can I do this in Python through method chaining?

Expected Output:

col1  col2    col3
dog   yellow  dave
cat   orange  pete
bird  yellow  pete
bird  red     tom

I know that there is a replace function but it works like the following:

df[col1].replace('old_val', 'new_val')

I want to do something like this (similar to the assign method where I can just keep adding new columns in the method):

#pseudocode
df.replace(col1 = mapping1, col2 = mapping2, col3 = mapping3)

How can I do this in pandas?

3 Answers 3

2

Use pd.Series.map function:

df.assign(col1=df['col1'].map(mapping1), col2=df['col2'].map(mapping2), col3=df['col3'].map(mapping3))
Sign up to request clarification or add additional context in comments.

Comments

1

Use DataFrame.replace:

d = {'col1': {1: 'dog', 2: 'cat', 3: 'bird'},
     'col2': {1: 'yellow', 2: 'orange', 3: 'red'},
     'col3': {1: 'dave', 2: 'pete', 3: 'tom'}}

out = df.replace(d)

Output:

   col1    col2  col3
0   dog  yellow  dave
1   cat  orange  pete
2  bird  yellow  pete
3  bird     red   tom

Comments

0

You can use the replace() method of the Pandas DataFrame in combination with method chaining to replace the numerical values in the data frame with the corresponding string values based on the given mappings. Here's an example code:

import pandas as pd

# Create the data frame
df = pd.DataFrame({
    'col1': [1, 2, 3, 3],
    'col2': [1, 2, 1, 3],
    'col3': [1, 2, 2, 3]
})

# Define the mappings
mapping_col1 = {1: 'dog', 2: 'cat', 3: 'bird'}
mapping_col2 = {1: 'yellow', 2: 'orange', 3: 'red'}
mapping_col3 = {1: 'dave', 2: 'pete', 3: 'tom'}

# Use method chaining to replace the numerical values with string values
df = df.replace({'col1': mapping_col1}).replace({'col2': mapping_col2}).replace({'col3': mapping_col3})

# Print the updated data frame
print(df)

This will output the following data frame with the numerical values replaced by the corresponding string values based on the given mappings:

   col1    col2  col3
0   dog  yellow  dave
1   cat  orange  pete
2  bird  yellow  pete
3  bird     red   tom

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.