Pandas Get Count of Each Row of DataFrame

  • Post author:
  • Post category:Pandas
  • Post last modified:October 5, 2023

In Pandas, You can get the count of each row of DataFrame using DataFrame.count() method. In order to get the row count you should use axis='columns' as an argument to the count() method. Note that the count() method ignores all None & nan values from the count.


# Syntax of df.count()
df.count(axis='columns')

Let’s see with an example


import pandas as pd
import numpy as np
technologies= {
    'Courses':["Spark","PySpark","Hadoop","Python","Pandas"],
    'Courses Fee' :[22000,25000,23000,24000,26000],
    'Duration':['30days','50days','30days', None,np.nan],
    'Discount':[1000,2300,1000,1200,2500]
          }
df = pd.DataFrame(technologies)
print(df)

Yields below output.


# Output:
   Courses  Courses Fee Duration  Discount
0    Spark        22000   30days      1000
1  PySpark        25000   50days      2300
2   Hadoop        23000   30days      1000
3   Python        24000     None      1200
4   Pandas        26000      NaN      2500

1. Pandas Get Count of Each DataFrame Row Example

Now, let’s run the DatFrame.count() to get the count of each row by ignoring None and Nan values.


# Pandas Get Count of Each DataFrame Row Example
df.count(axis='columns')

Yields below output. Note that Rows 3 and 4 are 3 as these two rows have None or Nan values.


# Output:
0    4
1    4
2    4
3    3
4    3

Happy Learning !!

References

Naveen

I am a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, I have honed my expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. My journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. I have started this SparkByExamples.com to share my experiences with the data as I come across. You can learn more about me at LinkedIn

Leave a Reply

You are currently viewing Pandas Get Count of Each Row of DataFrame