Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python
communitycreator

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

Onyejiaku Theophilus Chidalu

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))
Implementing the count() function

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
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring