Get Column Names by Pandas Data Frame Columns Property

How to get column labels in a Data Frame

Pandas Data Frame has the columns property that you may use to get the column labels in a data frame.

Syntax:

DataFrame.columns

In the example below, we will show you getting column labels of data frames that are created based on CSV and Excel files.

An example to get column labels of a CSV file

In the example below, we will load a CSV file by using the read_csv method of Pandas.

Our sample CSV file is shown below:

pandas-df-columns

This is used to create a data frame.

This is followed by using the columns property of the DF to display the column labels in the CSV file:

Code:

import pandas as pd

#Specifying CSV file

df = pd.read_csv('pandas_csv.csv')

#Display column labels

print(df.columns)

Output:

Index([‘Product ID’, ‘Product Name’, ‘Price’, ‘Status’], dtype=’object’)

The example of using an excel file and displaying its columns

This time, a data frame is created by using the read_excel method of Padnas.

Sample Excel sheet:

pandas-df-excel-cols

Then columns property of the Data Frame is used to display the labels in the data frame.

Python program:

import pandas as pd

#Specifying excel file to create a data frame

df_excel = pd.read_excel('test_pandas.xlsx')

#Display column labels

print(df_excel.columns)

Result:

Index([‘Product ID’, ‘Product Name’, ‘Price’, ‘Status’], dtype=’object’)

The example of creating a data frame and using columns property

In the Python program below, we have created a Pandas Data frame with three columns and also created three rows of data.

This is followed by displaying the data frame.

Finally, we used the columns property of the DF to display column labels of the data frame.

Code:

import pandas as pd

inflation_data = {

  "Year": [2015, 2016, 2016, 2017],

  "Inflation": ['3.25%', '2.15%', '3%', '1.5%']

}

#Creating a Data frame

df = pd.DataFrame(inflation_data)

#Display column labels

print(df.columns)

Output:

Index([‘Year’, ‘Inflation’], dtype=’object’)

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!