How to Get Column Names in Pandas
Last Updated :
28 Jun, 2024
While analyzing the real datasets which are often very huge in size, we might need to get the pandas column names in order to perform some certain operations. Let’s discuss how to get column names in the Pandas .
Syntax to Get Column Names in Pandas
# Get column names as an Index object
column_names = df.columns
Get Column Names in Pandas
First, let’s create a simple data frame with nba.csv file.
Python
# Import pandas package
import pandas as pd
# making data frame
data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")
# calling head() method
# storing in new variable
data_top = data.head()
# display
data_top
Output
Now let’s try to get the columns name from above dataset.
Get a list from Pandas DataFrame column
Example 1: Get Column Names from CSV
We can use Pandas Dataframe columns Property to get all the columns from a CSV fie in the form of list.
Python
# Import pandas package
import pandas as pd
# making data frame
data = pd.read_csv("nba.csv")
# list(data) or
list(data.columns)
Output:

Example 2: Iterate Over Columns of Pandas Dataframe
Here, we are loading the CSV file and iterating each column of CSV using the df.columns .
Python
# Import pandas package
import pandas as pd
# making data frame
data = pd.read_csv("nba.csv")
# iterating the columns
for col in data.columns:
print(col)
Output:
Name
Team
Number
Position
Age
Height
Weight
College
Salary
Get Column Names in Pandas using keys()
It will also give the columns of the dataframe.
Python
# Import pandas package
import pandas as pd
# making data frame
data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")
# calling keys() function
print(data.keys())
Output:
Index([Name, Team, Number, Position, Age, Height, Weight, College, Salary], dtype='object')
Get Column Names in Pandas column.values
The column.values method returns an array of index.
Python
# Import pandas package
import pandas as pd
# making data frame
data = pd.read_csv("nba.csv")
list(data.columns.values)
Output
[Name, Team, Number, Position, Age, Height, Weight, College, Salary]
Pandas List Column Names using tolist() Method
Using tolist() method with values with given the list of columns.
Python
# Import pandas package
import pandas as pd
# making data frame
data = pd.read_csv("nba.csv")
list(data.columns.values.tolist())
Output
[Name, Team, Number, Position, Age, Height, Weight, College, Salary]
Pandas Print Column Names using sorted() Method
The sorted() method will return the list of columns sorted in alphabetical order.
Python
# Import pandas package
import pandas as pd
# making data frame
data = pd.read_csv("nba.csv")
# using sorted() method
sorted(data)
Output
[Name, Team, Number, Position, Age, Height, Weight, College, Salary]
Please Login to comment...