Pandas DataFrame | count method
Start your free 7-days trial now!
Pandas DataFrame.count(~) method counts the number of non-missing values for each row or column of the DataFrame.
Parameters
1. axislink | string or int | optional
Whether to check each column or row:
Axis | Description |
|---|---|
| Count each column. |
| Count each row. |
By default, axis=0.
2. level | int or string | optional
The level to check. This is only relevant if the source DataFrame has MultiIndex.
3. numeric_onlylink | boolean | optional
If
True, then the method will perform the count on columns/rows of typenumberorboolean.If
False, then all columns/rows will be counted.
By default, numeric_only=False.
Return Value
A Series of int that indicates the number of missing values for each row/column of the source DataFrame.
Examples
Consider the following DataFrame:
df
A B0 NaN 31 NaN 4
Counting non-missing values column-wise
To count the number of non-missing values for each column:
df.count() # axis=0
A 0B 2dtype: int64
Here, we have 0 non-NaN values in column A, and 2 non-NaN values in B.
Counting non-missing values row-wise
To count the number of non-missing values for each row, set axis=1:
df.count(axis=1)
0 11 1dtype: int64
Here, we have 1 non-missing value in both row 0 and row 1.
Counting only numeric and boolean columns/rows
Consider the following DataFrame:
df
A B0 a 31 b 4
To count only numeric and boolean columns, set numeric_only=True:
df.count(numeric_only=True)
B 2dtype: int64
Notice how column A is ignored since it is a non-numeric type.