How to get pandas column names as a list?

Spread the love

Problem –

You have a dataframe and you want to get the names of the columns or headers in a list.

Solution –

Read a dataset for illustration

import pandas as pd
url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv"
df = pd.read_csv(url)
df.head()

Method 1 –

The easiest way to get the name of the columns or headers in pandas dataframe is simply passing the dataframe in a list.

list(df)

Method 2 –

Another way to get the name of columns or headers in pandas dataframe is using the DataFrame.columns attribute. The column attribute gives you the name of column as index object.

df.columns

Now to get the columns in a list, all you have to do is chain the tolist() method like this

df.columns.tolist()

1 . Pandas – How to change the order of columns in pandas.

2 . How to rename column names in pandas

Leave a Reply