What are different ways to get the column count of a DataFrame?
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 pddf = pd.DataFrame({'Name':['Dom', 'Celeste', 'Abhi', 'Gaby', 'Rachel', 'Sam'],'Age': [20,25,30,18,25,20]})row_count, col_count = df.shapeprint("The number of columns in df is %s" % (col_count,))
Explanation
- Line 1: We import the
pandasmodule. - Line 3: We create a DataFrame called
dffrom a dictionary. - Line 5: We obtain the row and column count of the
dfusing theshapeattribute. - 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 pddf = 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,))
Explanation
- Line 1: We import the
pandasmodule. - Line 3: We create a DataFrame called
dffrom a dictionary. - Line 5: We use the
columnsattribute to return the list of columns indf, and use thelenfunction to return the length of this list. This gives us the number of columns indf. - 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 pddf = 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))
Explanation
- Line 1: We import the
pandasmodule. - Line 3: We create a DataFrame called
dffrom a dictionary. - Line 6: We invoke the
info()method ondf. This prints basic information aboutdf, including the total number of columns in it.