How to get the number of columns in a pandas DataFrame in python ?

Published: April 11, 2020

Tags: Pandas; python;

DMCA.com Protection Status

Example of how to get the number of columns in a pandas DataFrame in python:

Create a simple dataframe with pandas

Let's start by creating a simple dataframe df:

>>> import pandas as pd
>>> import numpy as np
>>> data = np.arange(1,13)
>>> data = data.reshape(3,4)
>>> df = pd.DataFrame(data=data,columns=['a','b','c','d'])
>>> df
   a   b   c   d
0  1   2   3   4
1  5   6   7   8
2  9  10  11  12

Get the number of columns

To obtain the number of columns of a dataframe we can use the function len()

>>> len(df.columns)
4

References