How to get column labels in a Data Frame
Pandas Data Frame has the columns property you may use to get the column labels in a data frame.
Syntax:
In the example below, we will show you how to get column labels of data frames 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:
- 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:
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:
The 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:
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: