Pandas DataFrame.count: Count Non-NA Values in a DataFrame
Pandas DataFrame.count
The DataFrame.count
method in pandas counts the number of non-NA/null values along the specified axis of a DataFrame. It is a helpful method for analyzing data completeness.
Syntax
The syntax for DataFrame.count
is:
DataFrame.count(axis=0, numeric_only=False)
Here, DataFrame
refers to the pandas DataFrame on which the operation is performed.
Parameters
Parameter | Description |
---|---|
axis | Specifies the axis along which the counting is performed. Use 0 or 'index' for columns and 1 or 'columns' for rows. Defaults to 0 . |
numeric_only | If True , only counts numeric data types. If False , counts all data types. Defaults to False . |
Returns
A Series with counts of non-NA/null values along the specified axis. The index of the Series corresponds to the column or row labels of the DataFrame.
Examples
Counting Non-NA Values in a DataFrame
This example demonstrates how to use DataFrame.count
to count non-NA values in each column.
Python Program
import pandas as pd
# Create a DataFrame with missing values
df = pd.DataFrame({
'A': [1, 2, None, 4, 5],
'B': [None, 2, 3, 4, None],
'C': [1, 2, 3, 4, 5]
})
# Count non-NA values along columns
result = df.count(axis=0)
print(result)
Output
A 4
B 3
C 5
dtype: int64
Counting Non-NA Values Along Rows in a DataFrame
This example demonstrates counting non-NA values along the rows of a DataFrame using axis=1
.
Python Program
import pandas as pd
# Create a DataFrame with missing values
df = pd.DataFrame({
'A': [1, None, 3],
'B': [4, 5, None],
'C': [None, 8, 9]
})
# Count non-NA values along rows
result = df.count(axis=1)
print(result)
Output
0 2
1 2
2 2
dtype: int64
Counting Numeric Data Only in a DataFrame
This example shows how to use the numeric_only
parameter to count numeric data types only.
Python Program
import pandas as pd
# Create a DataFrame with mixed data types
df = pd.DataFrame({
'A': [1, 2, None],
'B': [4, None, 6],
'C': ['x', 'y', 'z']
})
# Count numeric data only
result = df.count(numeric_only=True)
print(result)
Output
A 2
B 2
dtype: int64
Counting Non-NA Values in an Empty DataFrame
This example demonstrates counting non-NA values in an empty DataFrame.
Python Program
import pandas as pd
# Create an empty DataFrame
df = pd.DataFrame()
# Count non-NA values
result = df.count()
print(result)
Output
Series([], dtype: int64)
Summary
In this tutorial, we explored the DataFrame.count
method in pandas. Key takeaways include:
- Using
count
to compute the number of non-NA values in DataFrame columns or rows. - Specifying the axis for counting (
axis=0
for columns,axis=1
for rows). - Using the
numeric_only
parameter to count numeric data types only. - Handling empty DataFrames gracefully.