What does the pandas DataFrame.index attribute do?

PandasServer Side ProgrammingProgramming

A DataFrame is a pandas data structure that is used to store the labeled data in a two-dimension, the labels can be anything like text data, integer values, and time sequence. by using these labels we can access elements of a given DataFrame and we can do data manipulations too.

In pandas.DataFrame the row labels are called indexes, If you want to get index labels separately then we can use pandas.DataFrame “index” attribute.

Example 1

In this example, we have applied the index attribute to the pandas DataFrame to get the row index labels.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame(list('abcdef'), columns=['Col1'])

print("DataFrame:")
print(df)

# get the index labels
result = df.index
print("Output:")
print(result)

Output

The output is given below −

DataFrame:
  Col1
0    a
1    b
2    c
3    d
4    e
5    f
Output:

RangeIndex(start=0, stop=6, step=1)

At the time of creating the DataFrame object, we haven’t initialized the index labels for this example. So the pandas.DataFrame Constructor automatically provided the range index values.

The index attribute accessed the auto-created row index label (RangeIndex values), and those are displayed in the above output block.

Example 2

Now, let us update the auto created row index values by sending a list of labels to the DataFrame.index attribute “df.index”.

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame(list('abcdef'), columns=['Col1'])
print("DataFrame:")
print(df)

# set the index labels
df.index = [10, 11, 12, 13, 14, 15]
print("Index values are Updated:")
print(df)

Output

The output is as follows −

DataFrame:
   Col1
0    a
1    b
2    c
3    d
4    e
5    f

Index values are Updated:
   Col1
10    a
11    b
12    c
13    d
14    e
15    f

The row index labels are updated from RangeIndex values to [10, 11, 12, 13, 14, 15].

raja
Updated on 08-Mar-2022 11:28:18

Advertisements