Dataframe makes data processing easy and fast. Well! in most of the scenarios, We have to play with the dataframe columns name. If you are also struggling and looking for How to get pandas column name? You are in the correct place. Here you will get a python program to display the column names.
There are so many ways to get column names from dataframe pandas. Each has its own advantages and disadvantages that depends on the situation. In order to understand them Lets first create a dummy dataframe. We will see how with live coding examples.
import pandas as pd
employee = {
'Name':['Ram', ' Sohan', 'Bob', 'Alica', 'Vanket'],
'Marks' :['27', '33', '26', '32', '54'],
'Earning':['100000', '500001', '300000', '170000', '100000000'],
'Location':['India', 'Pakistan', 'China', 'UK', 'America'],
'Rating':['4', '5', '1', '3', '1'] }
dataframe = pd.DataFrame(employee)
The below code will return the column name list. Here is the complete syntax.
list(dataframe .keys())
Output
Here typecasting is necessary as keys() function return index objects. In order to convert this object to the list, We need to add it as an argument for the list() method.
To fetch columns in pandas you can also use Dot operator. After that, you have to Typecast the results into the list with columns attribute. Like below
list(dataframe.columns)
Here dataframe.columns return index type object, hence need to be typecasted into the list object.
One of the easiest ways to get the column name is using the sorted() function. Below is the example for python to find the list of column names-
sorted(dataframe)
This is not the most recommended way to get the pandas column from the dataframe but It is the most familiar one. Using this technique you can easily print the python pandas columns header.
for columne_name in dataframe.columns:
print(columne_name)
I hope you must like this article. Keep reading and stay motivated.
Thanks
Data Science Learner Team