In the pandas
library, the DataFrame is a two-dimensional labeled data structure with columns that can be of different types. The index of a DataFrame helps in the quick retrieval of data and can be named for better understanding and clarity. In this article, we’ll explore how to set the index name for a DataFrame using various options.
DataFrame creation
Let’s start by creating a basic DataFrame
Output
Setting the index name
To set the index name of a DataFrame, you can simply assign a string to the name
attribute of the DataFrame’s index:
The DataFrame now looks like:
The index now has the name “ID”.
Setting index name while creating a dataframe
You can also set the index name directly when creating the DataFrame:
This produces the same result as the previous example.
Resetting the index name
To reset or remove the index name, simply assign None
to the name
attribute of the index: