In Pandas, the index column is a special column that identifies each row of a DataFrame with a unique label. You can access the index column of a DataFrame using the index
attribute.
Here are some examples:
Accessing the index values:
import pandas as pd # create a DataFrame data = {'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35]} df = pd.DataFrame(data) # print the index values print(df.index)
Output:
RangeIndex(start=0, stop=3, step=1)
Setting a column as index:
import pandas as pd # create a DataFrame data = {'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35]} df = pd.DataFrame(data) # set 'name' column as index df.set_index('name', inplace=True) # print the DataFrame with index print(df)
Output:
age name Alice 25 Bob 30 Charlie 35
In the above example, the set_index() method is used to set the ‘name’ column as the index of the DataFrame. The inplace=True parameter is used to modify the DataFrame in place. After setting the index, the DataFrame is printed with the index column displayed.