ADVERTISEMENT
ADVERTISEMENT

How to get a list from Pandas DataFrame column headers?

Given a DataFrame, we need access a list of column headers in this DataFrame.
Submitted by Pranit Sharma, on April 10, 2022

Columns are the different fields that contains their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Each column has a specific header/name. We can access the list of column headers with the help of pandas.DataFrame.columns.values.tolist() method.

pandas.DataFrame.columns.values.tolist() Method

First of all, DataFrame.columns returns all the column names from the DataFrame printed as Index. Then, tolist() method convert the columns as an array to a list.

To work with Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

Let us understand with an example.

# 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 »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.