Pandas tricks — Indexing

Shekhar Khandelwal
3 min readNov 12, 2020

--

Indexes in pandas dataframe are a very important aspect of data manipulations, as they are the best placeholders that can be used to do various data wrangling activities.

With this post, I will try to explain index in pandas data frames, how to deal with them and few use cases where they can be useful.

First of all, indexes are nothing but the row location in the data frame, by default it starts with 0.

Lets read a random csv file.

So as you can see, an index is by default provided to the dataframe, starting with 0.

If we want to start the index with 1 -

If we want to see the index details -

To store the index of the dataframe in a list for further iterative processings -

To make the index as one of the dataframe columns -

with reset_index(), you can see that the old indexes became the one of the columns, and the dataframe is by default provided new set of index, again starting with 0.

But if we just want to reset the index starting with 0 again, without getting a new column, use (drop=True) argument in reset_index() -

To set one of the columns as the index -

One use case why would we like to set a column as an index is, lets say we set the VALUE column as the index -

…and now we want to slice the dataframe to extract all the records that has value = 4.7, then we can use loc() method -

Still if we want to use the original index to process the dataframe, use iloc() method instead -

To manually set the index -

To create a new set of index, use reindex() -

In the new set of index, if the dataframe has similar index name, then the values are retained, and new indexes will be assigned NaN.

Git repo -https://github.com/shekharkhandelwal1983/pandas/blob/master/pandas_indexing.ipynb

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Shekhar Khandelwal
Shekhar Khandelwal

Written by Shekhar Khandelwal

Data Scientist with a majors in Computer Vision. Love to blog and share the knowledge with the data community.

No responses yet

Write a response