Predictive Hacks

Change multiple columns values with applymap

We will provide an example of how you can change multiple column values in pandas data frames using the applymap function. Assume that your data frame takes values 1,2,3 and you want to apply the following mapping function:

  • If 1 then 0
  • If 2 or 3 then 1
df = pd.DataFrame({'A':[1,1,2,2,3,3],
                   'B':[1,2,3,1,2,3]})
df
        A	B
0	1	1
1	1	2
2	2	3
3	2	1
4	3	2
5	3	3
# create the mapping dictionary
d = {1 : 0, 2: 1, 3: 1}

# apply it to all columns
df.applymap(d.get)

        A	B
0	0	0
1	0	1
2	1	1
3	1	0
4	1	1
5	1	1

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s