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.
Example 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 columns
cols = df.columns
#print the columns
print(cols)
Output
Index(['name', 'physics', 'chemistry', 'algebra'], dtype='object')
Example 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 columns
cols = df.columns
#print the columns
for i in range(len(cols)):
print(cols[i])
Output
name
physics
chemistry
algebra
Example 3: Print Columns using For Loop
You can use for loop to iterate over the columns 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 columns
cols = df.columns
#print the columns
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.