Pandas – How map() function works in pandas

Spread the love

pandas.Series.map –

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 = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/breast_cancer.csv"
df = pd.read_csv(url)
df.head()

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)
df.sample(5)

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