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.
shape
attributeThe 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.
DataFrame.shape
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,))
pandas
module.df
from a dictionary.df
using the shape
attribute.columns
attributeThe 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.
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,))
pandas
module.df
from a dictionary.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
.info()
methodThe info()
method returns basic information about the DataFrame. Part of the information that is returned is the DataFrame’s column count.
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))
pandas
module.df
from a dictionary.info()
method on df
. This prints basic information about df
, including the total number of columns in it.RELATED TAGS
CONTRIBUTOR
View all Courses