• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
[Tut] How Do I Get the Row Count of a Pandas DataFrame?

How Do I Get the Row Count of a Pandas DataFrame?

Overview

Problem Statement: Given a Pandas Dataframe, how to get the row count of the data frame?

Example: In the following example, we have a dataframe that has 5 rows in it. Thus, the question here is how do we get the number of rows in the dataframe? (Output expected is 5 in this case)

import pandas as pd df = pd.DataFrame({ 'col1': [10, 20, 30, 40, 50], 'col2': ['a', 'b', 'c', 'd', 'e'], 'col3': [True, False, True, None, False],
}) # Some way to print the number of rows which in this case is 5

Note: Pandas DataFrame is a 2 Dimensional data structure that is immutable and heterogeneous. This data structure has labelled axes rows and columns. A dataframe comprises three parts: data, rows, and columns.

In the above example the data frame used is as follows:

0 10 a True
1 20 b False
2 30 c True
3 40 d None
4 50 e False

Read more about Pandas Dataframes here: How to Create a DataFrame in Pandas?

Now that we have an idea about Pandas Dataframe and we also have a clear picture of the problem given, let’s dive into the different ways to get the row count of a Pandas DataFrame.

Method 1: Using len() or len(df.index) Approach: A very simple approach to find the number of rows in the given dataframe is to use the len() method.

Python’s built-in function len() returns the length of the given string, array, list, tuple, dictionary, or any other iterable. The type of the return value is an integer that represents the number of elements in this iterable.

Solution:

import pandas as pd df = pd.DataFrame({ 'col1': [10, 20, 30, 40, 50], 'col2': ['a', 'b', 'c', 'd', 'e'], 'col3': [True, False, True, None, False],
})
# Printing the dataframe
print(df)
l = len(df)
# Printing the number of rows
print("\nCount of Rows in Dataframe: ", l)

Output:

col1 col2 col3
0 10 a True
1 20 b False
2 30 c True
3 40 d None
4 50 e False Count of Rows in Dataframe: 5 Approach: Instead of using len(), you can use a quicker approach with the help of len(df.index). While df.index gives the count of rows in the dataframe, df.columns returns the number of columns in the dataframe.

Solution:

import pandas as pd
df = pd.DataFrame({ 'col1': [10, 20, 30, 40, 50], 'col2': ['a', 'b', 'c', 'd', 'e'], 'col3': [True, False, True, None, False],
})
print(df)
print()
print("Number of Rows: ", len(df.index))
print("Number of Columns: ", len(df.columns))

Output:

col1 col2 col3
0 10 a True
1 20 b False
2 30 c True
3 40 d None
4 50 e False Number of Rows: 5
Number of Columns: 3

Method 2: Using Dataframe Shape Approach: Another workaround to find the number of rows in the given dataframe is to use pandas.DataFrame.shape that will return a tuple. This tuple represents the dimensions of the Pandas DataFrame.
⦿ The first element of the tuple, i.e., df.shape gets the number of rows while,
⦿ the second element of the tuple, i.e., df.shape gets the number of columns.

Solution:

import pandas as pd
df = pd.DataFrame({ 'col1': [10, 20, 30, 40, 50], 'col2': ['a', 'b', 'c', 'd', 'e'], 'col3': [True, False, True, None, False],
})
print(df)
print()
print("Number of Rows: ", df.shape)
print("Number of Columns: ", df.shape)

Output:

col1 col2 col3
0 10 a True
1 20 b False
2 30 c True
3 40 d None
4 50 e False Number of Rows: 5
Number of Columns: 3

Method 3: Using DataFrame Axes Length Approach: The idea here is to track the range of a particular axis of the dataframe. Every DataFrame object consists of two axes: “axis 0” which represents the rows and “axis 1″which represents the columns. Now, the DataFrame.axes method is used to return the row and column axis labels.
⦿ df.axes is used to retrieve range of the rows of the Dataframe from the tuple whereas,
⦿ df.axes is used to retrieve the range of columns of the Dataframe.

Thus, you have to use the len() method after finding the row and column range using the axes() method to get the count of the number of rows.

Let’s have a look at the following solution:

import pandas as pd
df = pd.DataFrame({ 'col1': [10, 20, 30, 40, 50], 'col2': ['a', 'b', 'c', 'd', 'e'], 'col3': [True, False, True, None, False],
})
print(df)
print()
print("Count of rows: ", len(df.axes))
print("Count of columns: ", len(df.axes))

Output:

col1 col2 col3
0 10 a True
1 20 b False
2 30 c True
3 40 d None
4 50 e False Count of rows: 5
Count of columns: 3

Method 4: Using DataFrame Count Method

The df.count() method can be used to find the count of the number of rows in the Dataframe.

Example:

import pandas as pd
df = pd.DataFrame({ 'col1': [10, 20, 30, 40, 50], 'col2': ['a', 'b', 'c', 'd', 'e'], 'col3': [True, False, True, None, False],
})
print(df)
print()
print("Count of rows: ", df.count())

Output:

col1 col2 col3
0 10 a True
1 20 b False
2 30 c True
3 40 d None
4 50 e False Count of rows: 5

Caution: The Dataframe Count method ignores the None and Nan values in the columns and rows. If the row contains None values, then that row will be ignored while calculating the number of rows.

Example:

import pandas as pd
df = pd.DataFrame({ 'col1':[10, 20, None, 40, 50], 'col2': ['a', 'b', 'c', 'd', 'e'], 'col3': [True, False, True, None, False],
})
print("Count of rows: ", df.count()) # Count of rows: 4

Method 5: Using dataframe.info

Another effective method that helps us to get the number of rows in a dataframe is df.info. This method fetches a wide range of information about a DataFrame that includes the index dtype and columns, non-null values and memory usage.

Thus, you can use the df.info to get the number of rows in the dataframe. It also returns the Nan and None values included in a row.

Note: The df.info method is comparatively slower than other methods discussed as it retains various other information including the number of rows.

Solution:

import pandas as pd
df = pd.DataFrame({ 'col1': [10, 20, 30, 40, 50], 'col2': ['a', 'b', 'c', 'd', 'e'], 'col3': [True, False, True, None, False],
}) df.info()

Output:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 col1 5 non-null int64 1 col2 5 non-null object 2 col3 4 non-null object
dtypes: int64(1), object(2)
memory usage: 248.0+ bytes

Conclusion

In this tutorial, we learned about numerous methods to get the row count of a pandas DataFrame. Please stay tuned and subscribe for more such tips and tricks.

Learn Pandas the Fun Way by Solving Code Puzzles

If you want to boost your Pandas skills, consider checking out my puzzle-based learning book Coffee Break Pandas (Amazon Link).

It contains 74 hand-crafted Pandas puzzles including explanations. By solving each puzzle, you’ll get a score representing your skill level in Pandas. Can you become a Pandas Grandmaster?

Coffee Break Pandas offers a fun-based approach to data science mastery—and a truly gamified learning experience.

https://www.sickgaming.net/blog/2021/11/...dataframe/

Forum Jump:

 Users browsing this thread: 1 Guest(s) Discord Active Threads (Indie Deal) Handy Games, Offworld, Citi... Last Post: xSicKxBot Yesterday 10:43 AM » Replies: 0 » Views: 45 News - Pokemon-With-Guns Game Palworld C... Last Post: xSicKxBot Yesterday 10:42 AM » Replies: 0 » Views: 11 (Xbox 360) Mod Forza Horizon 2 with USB Last Post: tekashisama Yesterday 02:45 AM » Replies: 11 » Views: 10539 [Tut] How to Create a NumPy Array and Fi... Last Post: xSicKxBot Yesterday 02:45 AM » Replies: 0 » Views: 31 (Indie Deal) War Giveaways, Akupara, Hum... Last Post: xSicKxBot Yesterday 02:45 AM » Replies: 0 » Views: 13 News - Death’s Gambit: Afterlife Physica... Last Post: xSicKxBot Yesterday 02:44 AM » Replies: 0 » Views: 15 News - Xbox Game Pass Adding Another Day... Last Post: xSicKxBot Yesterday 02:44 AM » Replies: 0 » Views: 18 [Tut] How To Apply A Function To Each El... Last Post: xSicKxBot 01-26-2022 04:46 PM » Replies: 0 » Views: 28 (Indie Deal) Exotic Riddles Bundle, Dyin... Last Post: xSicKxBot 01-26-2022 04:45 PM » Replies: 0 » Views: 17 Mobile - Pokémon Sword and Shield myster... Last Post: xSicKxBot 01-26-2022 04:45 PM » Replies: 0 » Views: 14 Twitter Tweets by _SickGaming  