How to Count Number of Rows or Columns in a Pandas DataFrame
Let’s see how we can count the number of rows and columns in a Pandas DataFrame.
We’ll also include how to count non-null rows.
1. Count number of rows in a DataFrame
1.1. Number of rows
Any of the three options below are available to obtain the total number of rows (null or non-null).
len(df.index)
len(df)
df.shape[0]
1.2. Number of non-null rows
We can obtain non-null row count, which ignore NaN
values.
df.count()
We can also get the number of non-null values in first column.
df[df.columns[0]].count()
count()
returns a DataFrame of non-null counts for each column (i.e. non-null counts vary by column).
1.3. Number of rows per group
df.groupby(...).size()
size()
returns a Series (i.e. all columns in a group share the same row count).
1.4. Number of non-null rows per group
df.groupby(...).count()
Let’s obtain a non-null count for a specific column in one group.
df.groupby(...)['colName'].count()
When
count()
is called on a specific column, it will return a Series.
2. Count number of columns in a DataFrame
df.shape[1]
len(df.columns)