Count the number of rows and columns of a Pandas dataframe

There are indeed multiple ways to get the number of rows and columns of a Pandas DataFrame. Here's a summary of the methods you mentioned:

  1. len(df): Returns the number of rows in the DataFrame.
  2. len(df.index): Returns the number of rows in the DataFrame using the index.
  3. df.shape[0]: Returns the number of rows in the DataFrame using the shape attribute.
  4. df[df.columns[0]].count(): Returns the number of non-null values in a specific column (in this case, the first column).
  5. df.count(): Returns the count of non-null values for each column in the DataFrame.
  6. df.size: Returns the total number of elements in the DataFrame (number of rows multiplied by number of columns).

Each method has its own use case and can be chosen based on the specific requirement in your analysis.

First let's create a data frame with values.

import pandas as pd import numpy as np df = pd.DataFrame() df['Name'] = ['John', 'Doe', 'Bill','Jim','Harry','Ben'] df['TotalMarks'] = [82, 38, 63,22,55,40] df['Grade'] = ['A', 'E', 'B','E','C','D'] df['Promoted'] = [True, False,True,False,True,True] df
Name TotalMarks Grade Promoted 0 John 82 A True 1 Doe 38 E False 2 Bill 63 B True 3 Jim 22 E False 4 Harry 55 C True 5 Ben 40 D True

Pandas DataFrame row count

Using len()

The len() method can be used to find the number of rows in a Pandas DataFrame. When applied to a DataFrame, len() returns the number of rows, as it counts the number of elements in the DataFrame index.

row_count = len(df) # Return number of rows row_count
6

Or

row_count = len(df.index) # Return number of rows row_count
6

Using shape[0]

You can use shape[0] to find the number of rows in a Pandas DataFrame. The shape attribute of a DataFrame returns a tuple with the number of rows and columns, and by accessing the first element of the tuple (shape[0]), you get the number of rows.

row_count = df.shape[0] row_count
6

Another method:

row_count = df[df.columns[0]].count() row_count
6

Get Pandas DataFrame column count

Using shape[1]

col_count = df.shape[1] col_count
4

Using len()

col_count = len(df.columns) col_count
4

Pandas DataFrame column with row count

count = df.count() count
Name 6 TotalMarks 6 Grade 6 Promoted 6 dtype: int64

Total number of rows and column in DataFrame

df.size
24

Conclusion

To count the number of rows in a Pandas DataFrame, you can use the len() function or access the shape attribute and select the first element (shape[0]). To count the number of columns, you can use the shape attribute and select the second element (shape[1]) or use the len() function on the DataFrame's columns attribute.