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
print(type(df.columns)) # <class 'pandas.core.indexes.base.Index'>
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
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']
You might also like...
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.