How to Use count() in pandas: Syntax and Examples
In pandas, use the
count() method on a DataFrame or Series to count the number of non-missing (non-NaN) values. It returns counts per column by default for DataFrames, or a single count for Series.Syntax
The count() method syntax is:
DataFrame.count(axis=0, level=None, numeric_only=False)Series.count()
Parameters:
axis=0: Count along columns (0) or rows (1).level=None: For MultiIndex, count along a level.numeric_only=False: Count only numeric data if True.
It returns the count of non-NaN values.
python
df.count(axis=0, level=None, numeric_only=False)
Example
This example shows how to count non-missing values in each column of a DataFrame.
python
import pandas as pd import numpy as np data = {'A': [1, 2, np.nan, 4], 'B': [np.nan, 2, 3, 4], 'C': [1, np.nan, np.nan, 4]} df = pd.DataFrame(data) counts = df.count() print(counts)
Output
A 3
B 3
C 2
dtype: int64
Common Pitfalls
Common mistakes include:
- Expecting
count()to count all rows including NaNs (it only counts non-NaN values). - Using
count()on a Series without realizing it returns a single integer. - Confusing
count()withlen()which counts all rows regardless of missing data.
python
import pandas as pd import numpy as np data = {'A': [1, 2, np.nan, 4]} df = pd.DataFrame(data) # Wrong: expecting count to include NaNs wrong_count = len(df['A']) # counts all rows including NaN right_count = df['A'].count() # counts only non-NaN print(f"len(): {wrong_count}") print(f"count(): {right_count}")
Output
len(): 4
count(): 3
Quick Reference
Summary tips for using count() in pandas:
- Use
count()to count non-missing values only. - Default axis=0 counts per column; use axis=1 to count per row.
- For Series,
count()returns a single integer. - Use
len()to count total rows including missing values.
Key Takeaways
Use pandas
count() to count non-NaN values in DataFrames or Series.By default,
count() counts non-missing values per column in DataFrames.For Series,
count() returns a single integer count of non-NaN values.Do not confuse
count() with len(); the latter counts all rows including NaNs.Use
axis=1 in count() to count non-NaN values per row.