Pandas DataFrame ‘count()’ Method.


Pandas DataFrame ‘count()’ Method

Table Of Contents:

  1. Syntax Of ‘count( )’ Method In Pandas.
  2. Examples ‘count( )’ Method.

(1) Syntax:

DataFrame.count(axis=0, level=None, numeric_only=False)

Description:

  • Count non-NA cells for each column or row.
  • The values NoneNaNNaT, and optionally numpy.inf (depending on pandas.options.mode.use_inf_as_na) are considered NA.

Parameters:

  • axis{0 or ‘index’, 1 or ‘columns’}, default 0 :
    • If 0 or ‘index’ counts are generated for each column. If 1 or ‘columns’ counts are generated for each row.
  • level: int or str, optional –
    • If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a DataFrame. A str specifies the level name.
  • numeric_only: bool, default False –
    • Include only floatint or boolean data

Returns:

  • Series or DataFrame – For each column/row the number of non-NA/null entries. If level is specified returns a DataFrame.

(2) Examples Of count() Method:

Example-1

df = pd.DataFrame({"Person":
                   ["John", "Myla", "Lewis", "John", "Myla"],
                   "Age": [24., np.nan, 21., 33, 26],
                   "Single": [False, True, True, True, False]})
df

Output:

# Counting Each Column Value

df.count()

Output:

Person    5
Age       4
Single    5
dtype: int64

Note:

  • Notice the uncounted NA values.

# Counting Each Row Value

df.count(axis='columns')

Output:

0    3
1    2
2    3
3    3
4    3
dtype: int64

Leave a Reply

Your email address will not be published. Required fields are marked *