How to Get the List of Pandas DataFrame Column Headers?

In this tutorial, we will learn how to get the list of Pandas DataFrame column headers? By Pranit Sharma Last updated : April 12, 2023

Get Pandas DataFrame Column Headers

To get the list of Pandas DataFrame column headers, we use DataFrame.columns.values.tolist() method, it returns a list of column headers (column names) of a DataFrame.

The DataFrame.columns returns all the column names from the DataFrame printed as Index. And then, tolist() method convert the columns as an array to a list.

Let us understand with an example.

Python code to get the list of Pandas DataFrame column headers

# First, we will see how DataFrame.columns() 
# returns the column names as index

# Importing pandas package
import pandas as pd

# Creating a dictionary of student marks

d = {
    "Peter":[65,70,70,75],
    "Harry":[45,56,66,66],
    "Tom":[67,87,65,53],
    "John":[56,78,65,64]
}

# Now we will create DataFrame and 
# we will assign index name as subject names
df = pd.DataFrame(d,index=["Maths","Physics","Chemistry","English"])

# Column names as index first
print(df.columns,"\n")

# Now, we will see how tolist() method will 
# convert this array into list

# using tolist() method
print("List of column headers")
print(df.columns.values.tolist())

Output

Index(['Peter', 'Harry', 'Tom', 'John'], dtype='object') 

List of column headers
['Peter', 'Harry', 'Tom', 'John']

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.