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:
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:
1 2 3 4 5 6 7 8 9 |
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:
Then columns property of the Data Frame is used to display the labels in the data frame.
Python program:
1 2 3 4 5 6 7 8 9 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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’)