Get the number of columns in a Pandas DataFrame

Python

Pandas

DataFrame

Get column count

Luc B.

Python

Pandas

DataFrame

When working with DataFrames, one often needs the number of columns to carry out certain operations.

Code Example

Use the shape property of a DataFrame to obtain the number of columns.

import pandas as pd

# Create a DataFrame with 4 rows and 3 columns
penguins = pd.DataFrame({
    'name': ['Tim', 'Midge', 'Ronald', 'Amy'], 
    'favorite_food': ['fish', 'fish', 'fish', 'fingers'],
    'age': [2, 18, 12, 8],
})

# Get the number of columns here
rows, cols = penguins.shape
print('Number of Columns:', cols)
Number of Columns: 3

More Examples

Length of the Columns Array

Call len on the columns array to get the number of columns.

print('Number of Columns:', len(penguins.columns))
Number of Columns: 3