Trusted answers to developer questions

How to take count of non-NA values in a column or row

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Overview

The count() function is used to take count of non-NA (None, NaN, NaT values) cells present in a column or row or a DataFrame object.

Syntax

DataFrame.count(axis=0, level=None, numeric_only=False)
Syntax for the count() function in Pandas

Parameters

  • axis: This takes either 0 (or index) or 1 (or columns) for the counts to be generated for either the columns or the rows, respectively.
  • level: This takes a string level name to take count along with the given level.
  • numeric_only: This takes a boolean value indicating if only float, integer, or boolean values should be included.

Return value

This function returns a DataFrame showing the number of non-null entries in it.

Example

# A code to illustrate the count() function in Pandas
# importing the pandas and numpy libraries
import pandas as pd
import numpy as np
# creating a dataframe
df = pd.DataFrame({"Person":
["John", "Myla", "Lewis", "John", "Myla"],
"Age": [24., np.nan, 21., 33, 26],
"Single": [False, True, True, True, False]})
# printing the dataframe object
print(df)
# taking count of the non-NA values in present in the columns
print(" This is a dataframe of each columns and their Number of non-NA values: ", df.count())
# taking the count of the non-NA values in each of the rows
print("These are the number of non-NA values in each of the rows: ", df.count(axis=1))

Explanation

  • Lines 4–5: We import the necessary libraries.
  • Lines 8–11: We create a DataFrame object, df.
  • Line 15: We print df.
  • Line 18: We take count of the number of non-NA values in the columns of the DataFrame using the count() function.
  • Line 21: We take count of the number of non-NA values in the rows of the DataFrame using the count() function.

RELATED TAGS

pandas
python

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
Did you find this helpful?