What is the pandas.DataFrame.index attribute in Pandas?

Overview

The DataFrame.index attribute in Pandas returns the index(row labels) of a given DataFrame.

Syntax

The syntax for the DataFrame.index attribute is given below:

DataFrame.index attribute
Syntax for the DataFrame.index attribute in Pandas

Parameter value

Since it is an attribute, DataFrame.index does not take any parameter value.

Return value

The DataFrame.index attribute returns the index row labels of a DataFrame.

Example

# A code to illustrate the DataFrame.index attribute
# importing the pandas module
import pandas as pd
# creating a dataframe
df = pd.DataFrame({'Nme': {0: 'Alek', 1: 'Akim', 2: 'Cynthia'},
'Age': {0: 20, 1: 30, 2: 50},
'Sex': {0: "Male", 1: "Male", 2: "Female"}})
# printing the dataframe
print(df)
# obtaining the index labels of the DataFrame
index = df.index
print(index)

Explanation

  • Line 4: We import the pandas library.
  • Line 7: We create a DataFrame and we name it df using the pandas.DataFrame() function.
  • Line 12: We print the DataFrame, df.
  • Line 15: We obtain the row labels of the index of df using the DataFrame.index attribute. We assign the result to a variable, index.
  • Line 16: We print the value of the index variable.

Free Resources