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 moduleimport pandas as pd# creating a dataframedf = 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 dataframeprint(df)# obtaining the index labels of the DataFrameindex = df.indexprint(index)
Explanation
- Line 4: We import the
pandaslibrary. - Line 7: We create a DataFrame and we name it
dfusing thepandas.DataFrame()function. - Line 12: We print the DataFrame,
df. - Line 15: We obtain the row labels of the index of
dfusing theDataFrame.indexattribute. We assign the result to a variable,index. - Line 16: We print the value of the
indexvariable.