How to use list() Get Column Names as List in Pandas DataFrame In Python Pandas
In this method we are using Python built-in list() function the list(df.columns.values), function.
Python3
# import pandas library import pandas as pd # creating the dataframe df = pd.DataFrame({ 'PassengerId' : [ 892 , 893 , 894 , 895 , 896 , 897 , 898 , 899 ], 'PassengerClass' : [ 1 , 1 , 2 , 1 , 3 , 3 , 2 , 2 ], 'PassengerName' : [ 'John' , 'Prity' , 'Harry' , 'Smith' , 'James' , 'Amora' , 'Kiara' , 'Joseph' ], 'Age' : [ 32 , 54 , 71 , 21 , 37 , 9 , 11 , 54 ]}) print ( "The DataFrame :" ) display(df.head()) # multiple ways of getting column names as list print ( "\nThe column headers :" ) print ( "Column headers from list(df.columns.values):" , list (df.columns.values)) print ( "Column headers from list(df):" , list (df)) print ( "Column headers from list(df.columns):" , list (df.columns)) |
Output :
Note: Here we have display() function, which works inside Jupyter notebook for presentation purpose. For running in any other IDE, you can replace display() function with print() function.
Get list of column headers from a Pandas DataFrame
In this article, we will see, how to get all the column headers of a Pandas DataFrame as a list in Python.
The DataFrame.column.values attribute will return an array of column headers.
Contact Us