This tutorial shows how you can convert dataframe index as a column in Python. The basic syntax is to use reset_index() (see below).
df_name.reset_index()
Starting Dataframe for Examples 1 and 2
The following is the sample dataframe that will be used in Examples 1 and 2.
(Note that, Example 3 will use a different dataframe.)
import pandas as pd
d = {'Brand': ['Tesla', 'Ford','Toyota'], 'Count': [3, 4, 5]}
df = pd.DataFrame(data=d)
print(df)
The following the printout of the sample dataframe.
Brand Count 0 Tesla 3 1 Ford 4 2 Toyota 5
Example 1: use reset_index()
You can move the index of a dataframe as a column using reset_index() in Pandas. The following is the example.
df_changed=df.reset_index()
print(df_changed)
The following is the ouput.
index Brand Count 0 0 Tesla 3 1 1 Ford 4 2 2 Toyota 5
Example 2: Use inplace in reset_index()
You can add reset_index(inplace=True)
to save the index as a new column. The default is inplace=False
.
When you set inplace = True
, the reset_index
method will not create a new dataframe. Instead, it will directly modify and overwrite the original dataframe.
The follwoing is to apply reset_index(inplace=True)
.
# Applying inplace=True
df.reset_index(inplace=True)
# print the result
print("After using inplace:\n",df)
The following is the output. As we can see, it has been added a column named “index”. Note that, the true index is without column name in this case.
After using inplace: index Brand Count 0 0 Tesla 3 1 1 Ford 4 2 2 Toyota 5
Example 3: Use drop in reset_index()
You can use the drop=True
to not save the index as a column. The default is drop=False
.
Step 1: Create a dataframe
The following is the sample dataframe. The index is CA, MA, WA.
# Create a sample data frame
import pandas as pd
d = {'Brand': ['Tesla', 'Ford','Toyota'], 'Count': [3, 4, 5]}
df = pd.DataFrame(data=d,index=['CA','MA','WA'])
print(df)
The following is the original dataframe.
Brand Count CA Tesla 3 MA Ford 4 WA Toyota 5
Step 2:
Using drop=True
in reset_index()
# add drop=True
df_new=df.reset_index(drop=True)
print("Using drop=True:\n",df_new)
Using drop=True: Brand Count 0 Tesla 3 1 Ford 4 2 Toyota 5