Pandas – set_index() – How to set a column as index

Spread the love
set index in pandas

In this post you will learn –

  1. How to set a column as index in pandas
  2. How to set a multiple columns as index to create multiindex –

1 . How to set a column as index in pandas –

Let’s read the data to work with.

import pandas as pd

df = pd.read_csv("https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv")
df.head()

Let’s say you want to set the Type of customer as an index. To do that, you have to write.

df1 = df.set_index(['Type of Customer'])
df1

2 . How to set a multiple columns as index to create multiindex –

To set multiple columns as index to create multiindex, you need to pass the names of the columns in a list to the set_index method.

df2 = df.set_index(['Type of Customer','Gender'])
df2

Rating: 1 out of 5.

Leave a Reply