Get Pandas DataFrame Column Headers as a List

Get Pandas DataFrame Column Headers as a List

Pandas DataFrame columns give context into the values of the rows/entries we're working with. Sometimes, we need to remove them, when saving data for proprietary libraries that don't support columns, and sometimes we just want to export them in a different format.

In any case - saving the columns as a list is useful. Just accessing the columns gives us access to an Index object:

print(type(df.columns)) # <class 'pandas.core.indexes.base.Index'>

While the Index can act like a list, and can most certainly be used to again be inserted into a DataFrame - we can isolate a good old fashioned Pyhon list from it, using the tolist() method:

import pandas as pd
from sklearn.datasets import fetch_california_housing

data = fetch_california_housing(as_frame=True)

names = df.columns.tolist()
print(type(names)) # <class 'list'>
print(names) # ['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude', 'MedHouseVal']
Last Updated: July 7th, 2022
Was this helpful?
David LandupAuthor

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.


Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic

© 2013-2022 Stack Abuse. All rights reserved.