Get list of column headers from a Pandas DataFrame
Last Updated :
31 Aug, 2022
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.
pandas DataFrame column names
Using list() Get Column Names as List in Pandas DataFrame
In this method we are using Python built-in list() function the list(df.columns.values), function.
Python3
import pandas as pd
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())
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 :
Using list() to get columns list from pandas DataFrame
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.
Using tolist() Get Column Names as List in Pandas DataFrame
In this method, we are importing Python pandas module and creating a DataFrame to get the names of the columns in a list we are using the tolist(), function.
Python3
import pandas as pd
my_df = { 'Students' : [ 'A' , 'B' , 'C' , 'D' ],
'BMI' : [ 22.7 , 18.0 , 21.4 , 24.1 ],
'Religion' : [ 'Hindu' , 'Islam' ,
'Christian' , 'Sikh' ]}
df = pd.DataFrame(my_df)
display( "The DataFrame :" )
display(df)
print ( "The column headers :" )
print (df.columns.tolist())
|
Output :
The DataFrame :
Students BMI Religion
0 A 22.7 Hindu
1 B 18.0 Islam
2 C 21.4 Christian
3 D 24.1 Sikh
The column headers :
['Students', 'BMI', 'Religion']
Using list comprehension Get Column Names as List in Pandas DataFrame
In this method we are importing a Pandas module and creating a Dataframe to get the names of the columns in a list we are using the list comprehension.
Python3
import pandas as pd
my_df = { 'Students' : [ 'A' , 'B' , 'C' , 'D' ],
'BMI' : [ 22.7 , 18.0 , 21.4 , 24.1 ],
'Religion' : [ 'Hindu' , 'Islam' ,
'Christian' , 'Sikh' ]}
df = pd.DataFrame(my_df)
display( "The DataFrame :" )
display(df)
display( "The column headers :" )
print ([col for col in df])
|
Output:
List of column names using List comprehension
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...