Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas

What are different ways to get the column count of a DataFrame?

abhilash

Overview

Knowing the number of columns in a DataFrame is often helpful in data analysis and manipulation operations. Hence, it’s important to understand how to find the number of columns in a DataFrame.

Note: To learn more about pandas, check out this shot.

The shape attribute

The shape attribute of the pandas DataFrame returns a tuple of two elements. The element at index 1 indicates the number of columns of the dataframe.

Syntax

DataFrame.shape

Code example

import pandas as pd

df = pd.DataFrame({'Name':['Dom', 'Celeste', 'Abhi', 'Gaby', 'Rachel', 'Sam'],'Age':  [20,25,30,18,25,20]})

row_count, col_count = df.shape

print("The number of columns in df is %s" % (col_count,))
Implementing the shape attribute

Explanation

  • Line 1: We import the pandas module.
  • Line 3: We create a DataFrame called df from a dictionary.
  • Line 5: We obtain the row and column count of the df using the shape attribute.
  • Line 7: We print the column count.

The columns attribute

The columns attribute returns all the columns of the DataFrame. Finding the length of the columns attribute using the len function gives the number of columns of the DataFrame.

Code example

import pandas as pd

df = pd.DataFrame({'Name':['Dom', 'Celeste', 'Abhi', 'Gaby', 'Rachel', 'Sam'],'Age':  [20,25,30,18,25,20]})

col_count = len(df.columns)

print("The number of columns in df is %s" % (col_count,))
Implementing the columns attribute

Explanation

  • Line 1: We import the pandas module.
  • Line 3: We create a DataFrame called df from a dictionary.
  • Line 5: We use the columns attribute to return the list of columns in df, and use the len function to return the length of this list. This gives us the number of columns in df.
  • Line 7: We print the column count.

The info() method

The info() method returns basic information about the DataFrame. Part of the information that is returned is the DataFrame’s column count.

Code example

import pandas as pd

df = pd.DataFrame({'Name':['Dom', 'Celeste', 'Abhi', 'Gaby', 'Rachel', 'Sam'],'Age':  [20,25,30,18,25,20]})

print("With verbose set to True")
print(df.info())

print("-" * 8)
print("With verbose set to False")
print(df.info(verbose=False))
Implementing the info() method

Explanation

  • Line 1: We import the pandas module.
  • Line 3: We create a DataFrame called df from a dictionary.
  • Line 6: We invoke the info() method on df. This prints basic information about df, including the total number of columns in it.

RELATED TAGS

pandas
RELATED COURSES

View all Courses

Keep Exploring