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 Python 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: April 12th, 2023
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.

Ā© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms