8 different ways to get column names from pandas DataFrame
In this article, I will discuss the different ways to get the column names in pandas DataFrame
First, create a pandas DataFrame
import pandas as pd
df = pd.DataFrame({'col1':['A', 'B', 'C', 'D', 'E'], 'col2':[1, 2, 3, 4, 5], 'col3':[0.1, 0.2, 0.3, 0.4, 0.5]})
df.head(2)
# output
col1 col2 col3
0 A 1 0.1
1 B 2 0.2
Now, let’s check different methods to get the column names from pandas DataFrame
Get column names using list
function
list(df)
# output
['col1', 'col2', 'col3']
Get column names using * iterable unpacking operator
# it works in Python >=3.5
# as a list
[*df]
# output
['col1', 'col2', 'col3']
# as a tuple
*df,
# output
('col1', 'col2', 'col3')
# as a set
{*df}
# output
{'col3', 'col2', 'col1'} # Note: column names are not in original order
Get column names using DataFrame columns
attribute
It returns pandas index
df.columns
# output
Index(['col1', 'col2', 'col3'], dtype='object')
# column names as a list
list(df.columns)
# output
['col1', 'col2', 'col3']
df.columns.tolist() # Note: this is fastest method
# output
['col1', 'col2', 'col3']
Get column names using DataFrame columns.values
method
This method returns the column names as NumPy array
df.columns.values
# output
array(['col1', 'col2', 'col3'], dtype=object)
Get column names using sorted
function
This method returns the column names as a list in alphabetical order
sorted(df)
# output
['col1', 'col2', 'col3'] # Note: column names are not in original order
Get column names using keys()
function
It returns pandas index
df.keys()
# output
Index(['col1', 'col2', 'col3'], dtype='object')
Get column names using list comprehension
print([col_name for col_name in df])
# output
['col1', 'col2', 'col3']
Get column names and their data types
df.dtypes
# output
col1 object
col2 int64
col3 float64
dtype: object
Enhance your skills with courses on Python and pandas
- Python for Data Analysis: Pandas & NumPy
- Mastering Data Analysis with Pandas: Learning Path Part 1
- Data Analysis Using Python
- Python for Data Science, AI & Development
- Python 3 Programming Specialization
References
If you have any questions, comments or recommendations, please email me at reneshbe@gmail.com
This work is licensed under a Creative Commons Attribution 4.0 International License