Q:

How to get a list from Pandas DataFrame column headers?

belongs to collection: Python Pandas Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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']

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to get the number of rows in DataFrame?... >>
<< How to change the order of DataFrame columns?...