Compute a per-row completeness score for a pandas DataFrame
Quick Overview
Write a pandas function that scores each row of a DataFrame by the fraction of its cells that are not missing. It tests vectorized boolean masks, row-wise aggregation, keeping the index and dtype of the result, and how pandas treats different kinds of missing values.
Compute a per-row completeness score for a pandas DataFrame
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `row_completeness(df)` returning each row's completeness score: (count of non-NA cells) / (total number of columns), as `float64` on a 0.0-1.0 scale.
The result must meet these requirements:
- Return a `float64` `Series` named `'completeness'`.
- Keep `df`'s original index and row order: do not sort or reset.
- Do not filter rows or return a modified frame.
Example with 5 columns, where `r1` has all 5 cells filled, `r2` has none, and `r3` has 2 of 5:
```python
import numpy as np
import pandas as pd
df = pd.DataFrame(
{
'a': [1.0, np.nan, 3.0],
'b': [2.0, np.nan, np.nan],
'c': [4.0, np.nan, 6.0],
'd': [7.0, np.nan, np.nan],
'e': [8.0, np.nan, np.nan],
},
index=['r1', 'r2', 'r3'],
)
row_completeness(df)
```
```text
r1 1.0
r2 0.0
r3 0.4
Name: completeness, dtype: float64
```
```hint Think in masks
pandas can turn the whole frame into a True/False presence mask in one call. Consider what a row-wise aggregate of booleans gives you.
```
### Constraints & Assumptions
- The frame can mix numeric, text and datetime columns, and its index can hold any labels, including duplicates.
### What a Strong Answer Covers
- A vectorized presence mask instead of a Python loop over rows.
- Dividing by the total number of columns, so the score is a fraction of all columns.
- A `float64` Series named `completeness` that keeps the original index and row order.
- What counts as missing across dtypes, and what happens with zero rows or zero columns.
### Follow-up Questions
- How does `notna()` treat `NaT` and `None`?
- How would you change the score if some columns matter more than others?
- Some sources write missing values as empty strings or as -1. How would you count those as missing?
Overview: Write a pandas function that scores each row of a DataFrame by the fraction of its cells that are not missing. It tests vectorized boolean masks, row-wise aggregation, keeping the index and dtype of the result, and how pandas treats different kinds of missing values.
Write row_completeness(df) returning each row's completeness score: (count of non-NA cells) / (total number of columns), as float64 on a 0.0-1.0 scale.
The result must meet these requirements:
Return a
float64Series
named
'completeness'
.
Keep
df
's original index and row order: do not sort or reset.
Do not filter rows or return a modified frame.
Example with 5 columns, where r1 has all 5 cells filled, r2 has none, and r3 has 2 of 5: