0
0
Pandasdata~5 mins

columns and index attributes in Pandas

Choose your learning style9 modes available
Introduction
Columns and index attributes help you see and organize the labels of your data in tables. They make it easy to find and work with your data.
When you want to check the names of all columns in your data table.
When you need to rename or reorder columns to make data clearer.
When you want to see or change the row labels (index) for better data access.
When you want to select data by column or row names instead of positions.
When you want to add meaningful labels to your data for easier understanding.
Syntax
Pandas
dataframe.columns

dataframe.index
The columns attribute shows the list of column names in your table.
The index attribute shows the row labels, which can be numbers or names.
Examples
This example creates a simple table and prints the column names and row labels.
Pandas
import pandas as pd

data = {'Name': ['Anna', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)

print(df.columns)
print(df.index)
Here, we rename the columns to new names.
Pandas
df.columns = ['First Name', 'Years']
print(df.columns)
This changes the row labels from numbers to letters.
Pandas
df.index = ['a', 'b']
print(df.index)
Sample Program
This program creates a table of cities and populations, shows the original column and index labels, then renames them and shows the new labels.
Pandas
import pandas as pd

data = {'City': ['Paris', 'London', 'Berlin'], 'Population': [2148000, 8982000, 3769000]}
df = pd.DataFrame(data)

# Show original columns and index
print('Columns:', df.columns)
print('Index:', df.index)

# Rename columns
df.columns = ['City Name', 'Number of People']

# Change index labels
df.index = ['a', 'b', 'c']

print('New Columns:', df.columns)
print('New Index:', df.index)
OutputSuccess
Important Notes
Changing columns or index labels does not change the data itself, only the labels.
You can use these attributes to select data by name, which is easier than using numbers.
The index can be any labels, not just numbers, which helps when your rows have meaningful names.
Summary
Columns attribute shows or sets the names of the data table's columns.
Index attribute shows or sets the row labels for easier data access.
Renaming columns or index helps make data clearer and easier to work with.