While working with pandas dataframes it may happen that you require a list of all the column names present in a dataframe. You can use df.columns
to get the column names but it returns them as an Index object. In this tutorial, we’ll show some of the different ways in which you can get the column names of a dataframe as a list which gives you more flexibility for further usage.
How to get the list of column names of a Pandas dataframe?
You can use the list()
function in Python to get the column names of a Pandas dataframe as a list. Pass the dataframe as an argument to the list()
function. The following is the syntax –
# Method 1 list(df)
There are alternate methods as well to get the column names as a list. For example, you can use df.columns.values.tolist()
or a list comprehension. The following is the syntax of these methods –
# Method 2 df.columns.values.tolist() # Method 3 - list comprehension [col for col in df]
Examples
Let’s now look at some examples to get the column names of a dataframe as a list.
First, let’s create a sample dataframe that we’ll be using throughout this tutorial.
import pandas as pd data = { "Name": ["Google, LLC", "Microsoft Corporation", "Tesla, Inc."], "Symbol": ["GOOG", "MSFT", "TSLA"], "Shares": [100, 50, 80], } # create dataframe df = pd.DataFrame(data) # display dataframe df
Here, df
is a dataframe storing information on a sample portfolio of US companies with their Name, Stock Symbol, and the number of shares in the portfolio.
Let’s see what we get accessing the columns attribute of the dataframe df.
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
print(df.columns)
Output:
Index(['Name', 'Symbol', 'Shares'], dtype='object')
We see that an Index
object with the column names is returned. It would be convenient if we could have it as a simple list.
Using the list()
function
Pass the dataframe to the list()
function to get the list of column names.
print(list(df))
Output:
['Name', 'Symbol', 'Shares']
Using df.columns.values.tolist()
Alternatively, you can also use the df.columns.values.tolist()
method. We know that df.columns
returns an Index, now .values
on it returns an array and it has a helper function .tolist()
to return a list.
print(df.columns.values.tolist())
Output:
['Name', 'Symbol', 'Shares']
We get the same result as above.
Using list comprehension
You can also get the columns as a list using list comprehension.
print([col for col in df])
Output:
['Name', 'Symbol', 'Shares']
Comparing the methods
Now let’s see which of the three methods shown above is the fastest. For this, we’ll be using the %timeit
magic function.
%timeit list(df) %timeit df.columns.values.tolist() %timeit [col for col in df]
Output:
4.78 µs ± 592 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) 1.03 µs ± 113 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 4.31 µs ± 435 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
We find that df.columns.values.tolist()
is the fastest of the three. Also, note that the list()
and the list comprehension methods are comparable to each other and differences might occur when working with large dataframes.
There are other ways as well to get column names as a list for a pandas dataframe but they may be more or less an extension or variation of the above three methods. For more, refer to this thread on Stack Overflow.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having pandas version 1.0.5
More on Pandas DataFrames –
- Pandas – Sort a DataFrame
- Change Order of Columns of a Pandas DataFrame
- Pandas DataFrame to a List in Python
- Pandas – Count of Unique Values in Each Column
- Pandas – Replace Values in a DataFrame
- Pandas – Filter DataFrame for multiple conditions
- Pandas – Random Sample of Rows
- Pandas – Random Sample of Columns
- Save Pandas DataFrame to a CSV file
- Pandas – Save DataFrame to an Excel file
- Create a Pandas DataFrame from Dictionary
- Convert Pandas DataFrame to a Dictionary
- Drop Duplicates from a Pandas DataFrame
- Concat DataFrames in Pandas
- Append Rows to a Pandas DataFrame
- Compare Two DataFrames for Equality in Pandas
- Get Column Names as List in Pandas DataFrame
- Select One or More Columns in Pandas
- Pandas – Rename Column Names
- Pandas – Drop one or more Columns from a Dataframe
- Pandas – Iterate over Rows of a Dataframe
- How to Reset Index of a Pandas DataFrame?
- Read CSV files using Pandas – With Examples
- Apply a Function to a Pandas DataFrame
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.