There is a time when we want to do manipulation on the index column of the dataframe. Doing manipulation After Converting index to a column is very easy. In this tutorial, I will show step by step guide to convert index to columns in pandas.
There will be two methods that will be used here. One is df.reset_index() and the other is df.set_index(). You will know more about in coding demonstration part. The syntax for both of them is below.
Another Method is also used which is df. rename().
Steps to Convert Index to Column in Pandas
Step 1: Import all the necessary libraries.
The most basic step is to import all the necessary libraries. Here I am using three python modules that are NumPy, DateTime, and pandas. The datetime is used for the creation of time-series data. Let’s import all of them.
import numpy as np import pandas as pd import datetime
Step 2: Create a Sample Dataframe with index column.
Before converting index to column in pandas, let’s create a dataframe. In our example, I am creating a time-series dataframe. Execute the code given below to create it. I will not go on the explanation of the codes for dataframe creation. As it can lead to a long post. Just run it.
todays_date = datetime.datetime.now().date() index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D') columns = ['A','B', 'C'] data = np.array([np.arange(10)]*3).T df = pd.DataFrame(data,index=index, columns=columns)
Step 3: Covert Index to Column.
To convert index to column you have to use df.reset_index(df,inplace=True) method with your input dataframe. The inplace=True argument allows any changes to dataframe permanently.
Execute the following lines of code for conversion.
You will get the following output.
You can see in the output the date column which was index is changed to a column with the name “index“. Now you can manipulate it easily.
For example, I don’t want the name “index” and want to change it to “date“. To do so I will use the df.rename() method. Just run the code given below.
You can see index column is rename to “date“.
Set column as index In Pandas
The above step was to convert index to column in pandas. In this section, I will show you to set any column as index. And the method to do so is df.set_index(“your_column_name,inplace=True). For example I want to set column A as index then I will use the following code.
You should also note that you renaming is allowed as an index only when all the values that column is unique.
That’s all for now.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.