4.2 C
London
Friday, December 20, 2024
HomePandas in PythonGeneral Functions in PythonHow to List All Column Names in Pandas (4 Methods)

How to List All Column Names in Pandas (4 Methods)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use one of the following four methods to list all column names of a pandas DataFrame:

Method 1: Use Brackets

[column for column in df]

Method 2: Use tolist()

df.columns.values.tolist()

Method 3: Use list()

list(df)

Method 4: Use list() with column values

list(df.columns.values)

The following examples show how to use each of these methods with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23],
                   'assists': [5, 7, 7, 9, 12, 9],
                   'rebounds': [11, 8, 10, 6, 6, 5],
                   'blocks': [6, 6, 3, 2, 7, 9]})

#view DataFrame
df

	points	assists	rebounds blocks
0	25	5	11	 6
1	12	7	8	 6
2	15	7	10	 3
3	14	9	6	 2
4	19	12	6	 7
5	23	9	5	 9

Method 1: Use Brackets

The following code shows how to list all column names of a pandas DataFrame using brackets:

[column for column in df]

['points', 'assists', 'rebounds', 'blocks']

Method 2: Use tolist()

The following code shows how to list all column names using the .tolist() function:

df.columns.values.tolist()

['points', 'assists', 'rebounds', 'blocks'] 

Method 3: Use list()

The following code shows how to list all column names using the list() function:

list(df)

['points', 'assists', 'rebounds', 'blocks'] 

Method 4: Use list() with column values

The following code shows how to list all column names using the list() function with column values:

list(df.columns.values)

['points', 'assists', 'rebounds', 'blocks'] 

Notice that all four methods return the same results.

Note that for extremely large DataFrames, the df.columns.values.tolist() method tends to perform the fastest.

Additional Resources

The following tutorials explain how to perform other common functions with columns of a pandas DataFrame:

How to Drop Columns in Pandas
How to Exclude Columns in Pandas
How to Apply a Function to Selected Columns in Pandas
How to Change the Order of Columns in Pandas DataFrame

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories