Pandas – How map() function works in pandas

Spread the love –

map function in pandas is a series method. It helps you map values in a series with different values of you choice.

Let’s read a data to understand this

import pandas as pd
url = ""
df = pd.read_csv(url)

The diagnosis column contains two values M and B.

B – B stands for Benign, Which means the cell is non cancerous. The patient is not sick.

M – M stands for Malignant, which means the cell is cancerous. The patient is sick.

Now, suppose you want to change these values. You want to map M to 1 and B to 0.

# map values
values = {"B": 0, "M": 1}
df["diagnosis"] = df["diagnosis"].map(values)

You can see that all the values in diagnosis columns has been replaced or mapped with the new values.

Rating: 1 out of 5.

Leave a Reply