Get Column Names of Pandas DataFrame - Examples


Get DataFrame Column Names

To get the column names of DataFrame, use DataFrame.columns property.

The syntax to use columns property of a DataFrame is

DataFrame.columns

The columns property returns an object of type Index. We could access individual names using any looping technique in Python.

Examples

1. Print DataFrame column names

In this example, we get the dataframe column names and print them.

Python Program

import pandas as pd

# Initialize a DataFrame
df = pd.DataFrame(
	[['Amol', 72, 67, 91],
	['Lini', 78, 69, 87],
	['Kiku', 74, 56, 88],
	['Ajit', 54, 76, 78]],
	columns=['name', 'physics', 'chemistry', 'algebra'])	

# Get the DataFrame column names
cols = df.columns 

# Print the column names
print(cols)

Output

Index(['name', 'physics', 'chemistry', 'algebra'], dtype='object')

2. Access individual column names using index

You can access individual column names using the index.

Python Program

import pandas as pd

# Initialize a DataFrame
df = pd.DataFrame(
	[['Amol', 72, 67, 91],
	['Lini', 78, 69, 87],
	['Kiku', 74, 56, 88],
	['Ajit', 54, 76, 78]],
	columns=['name', 'physics', 'chemistry', 'algebra'])	

# Get the DataFrame column names
cols = df.columns 

# Print the column names
for i in range(len(cols)):
	print(cols[i])

Output

name
physics
chemistry
algebra

3. Print column names using For loop

You can use a For loop to iterate over the column names of DataFrame.

Python Program

import pandas as pd

# Initialize a dataframe
df = pd.DataFrame(
	[['Amol', 72, 67, 91],
	['Lini', 78, 69, 87],
	['Kiku', 74, 56, 88],
	['Ajit', 54, 76, 78]],
	columns=['name', 'physics', 'chemistry', 'algebra'])	

# Get the DataFrame column names
cols = df.columns 

# Print the column names using For loop
for column in cols:
	print(column)

Output

name
physics
chemistry
algebra

Summary

In this Pandas Tutorial, we extracted the column names from DataFrame using DataFrame.column property.