Radiology Claims Spend Summary with Fiscal-Month Mapping in pandas
SQL & DataModel answerLast updated
Clean a small claims CSV in pandas: sum spend per procedure group, compute each group's share of the total, and derive an October-based fiscal month without row loops.
You are given a small export of radiology claims. Each row has a claim id, a procedure group, a service timestamp, and the amount paid. Timestamps arrive as plain strings (object dtype), some amounts are negative because they are adjustments, and some amounts are blank.
claim_id,procedure_group,service_dt,paid_amt
1001,CT,2020-07-01 13:05:00,120.00
1002,MRI,2020-10-15 09:30:00,250.00
1003,CT,2020-10-20 11:00:00,-20.00
1004,XRay,2020-12-05 08:00:00,80.00
1005,MRI,2020-01-02 14:10:00,
Using Python and pandas, do the following.
- Load and summarize. Read the data defensively, with explicit dtypes and deliberate date handling. Treat a blank
paid_amtas 0 for aggregation, keep negative amounts as they are, and make sure type conversion does not introduce stray NaNs. Produce a table withprocedure_groupandpaid_amt_sum(rounded to 2 decimals). - Share of total. Add
pct_of_total, each group's share of the overall paid amount on a 0 to 100 scale with 2 decimals. The total must come from the cleaned values and must not be double-counted. - Fiscal month. Convert
service_dtto a real datetime and add an integer columnfiscal_month. The fiscal year starts on October 1, so October is 1, November is 2, and so on through September, which is 12. Unparseable or missing dates should becomeNaT, and theirfiscal_monthshould be 0 (unknown). Print the final dtypes and show that the computation is vectorized, with no per-row Python loops.
A reviewer's note says that 2020-10-15 "should come out as fiscal_month = 2". Check that claim against the rule above and say what you do about it.
State your assumptions and explain your choices, including the pitfalls you avoided.
Hints
Hint 1
Read `service_dt` as a string and convert it yourself with `pd.to_datetime(..., errors='coerce')`. That way a single bad value cannot silently leave the whole column as `object`.
Hint 2
Fill missing `paid_amt` once, right after loading, and derive everything from that cleaned column. Aggregate first, take the total as the sum of the unrounded group sums, then round only for display.
Hint 3
A month-to-fiscal-month mapping with October as the start is a modular expression on `dt.month`: shift by the start month, wrap with `% 12`, and add 1. Then apply `fillna(0).astype('int64')`. Work out what October maps to under this rule and compare it with the reviewer's claim.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem comes down to three habits: clean once, aggregate before computing ratios, and keep the date logic vectorized.
1. Defensive loading
- Pass an explicit
dtypemap toread_csv. IDs and group names becomestring, andpaid_amtbecomesfloat64, so a blank field turns into NaN instead of making pandas guess a type. - Read
service_dtas a string and convert it later withpd.to_datetime(..., errors="coerce"). Relying onread_csv(parse_dates=...)is risky: if even one value cannot be parsed, pandas leaves the entire column asobjectwithout complaint. An explicit coerce always yieldsdatetime64[ns], withNaTonly where the input was bad. - Fill missing
paid_amtwith 0 immediately after loading. Do not drop negatives, because they are adjustments that net against charges (CT: 120 - 20 = 100).
2. Aggregate, then compute percentages
- Compute
sums = df.groupby("procedure_group")["paid_amt"].sum(). - Take
total = sums.sum()from the unrounded sums. Becausegroupbypartitions the rows, this equals the row-level total, so nothing is counted twice. Do not merge the total back onto the rows and then sum again. - Then
pct = sums / total * 100. Round only at the very end. Guard againsttotal == 0to avoid dividing by zero.
3. Fiscal month
With a fiscal year starting in month s (here 10):
fiscal_month = (calendar_month - s) % 12 + 1
This maps October to 1, November to 2, December to 3, January to 4, and September to 12. Every operation is a column-level operation on dt.month. For NaT, dt.month yields NaN, which propagates through the arithmetic. Then fillna(0).astype("int64") produces the final integer column with 0 meaning "unknown".
The reviewer's claim
Under the stated rule (fiscal year starts October 1, October = 1), 2020-10-15 maps to 1, not 2. A result of 2 for October would require the fiscal year to start in September, which contradicts the rule. The right response is to flag the inconsistency, implement the rule as written, and validate with checks that follow from it (for example Oct to 1, Nov to 2, Dec to 3). Do not special-case the code to satisfy a check that disagrees with the specification.
Code
import io
import numpy as np
import pandas as pd
RAW = """claim_id,procedure_group,service_dt,paid_amt
1001,CT,2020-07-01 13:05:00,120.00
1002,MRI,2020-10-15 09:30:00,250.00
1003,CT,2020-10-20 11:00:00,-20.00
1004,XRay,2020-12-05 08:00:00,80.00
1005,MRI,2020-01-02 14:10:00,
"""
FISCAL_START = 10
def load_claims(src) -> pd.DataFrame:
df = pd.read_csv(
src,
dtype={
"claim_id": "string",
"procedure_group": "string",
"service_dt": "string",
"paid_amt": "float64",
},
)
df["procedure_group"] = df["procedure_group"].str.strip()
df["paid_amt"] = df["paid_amt"].fillna(0.0) # missing money -> 0, negatives kept
return df
def spend_by_group(df: pd.DataFrame) -> pd.DataFrame:
sums = df.groupby("procedure_group")["paid_amt"].sum()
total = sums.sum() # unrounded, computed once
pct = sums / total * 100 if total != 0 else pd.Series(np.nan, index=sums.index)
return (
pd.DataFrame({
"procedure_group": sums.index,
"paid_amt_sum": sums.round(2).to_numpy(),
"pct_of_total": pct.round(2).to_numpy(),
})
.sort_values("paid_amt_sum", ascending=False, ignore_index=True)
)
def add_fiscal_month(df: pd.DataFrame, start: int = FISCAL_START) -> pd.DataFrame:
df = df.copy()
df["service_dt"] = pd.to_datetime(df["service_dt"], errors="coerce")
month = df["service_dt"].dt.month # float, NaN where NaT
df["fiscal_month"] = ((month - start) % 12 + 1).fillna(0).astype("int64")
return df
if __name__ == "__main__":
claims = load_claims(io.StringIO(RAW))
print(spend_by_group(claims))
claims = add_fiscal_month(claims)
print(claims[["claim_id", "service_dt", "fiscal_month"]])
print(claims.dtypes)
fm = claims.set_index("claim_id")["fiscal_month"]
assert fm["1002"] == 1 # Oct -> 1 under the stated rule
assert fm["1004"] == 3 # Dec -> 3
assert fm["1001"] == 10 # Jul -> 10
assert fm["1005"] == 4 # Jan -> 4
bad = add_fiscal_month(pd.DataFrame(
{"service_dt": ["2020-11-01 00:00:00", "not a date", None]}))
assert bad["fiscal_month"].tolist() == [2, 0, 0]
Expected output
| procedure_group | paid_amt_sum | pct_of_total |
|---|---|---|
| MRI | 250.00 | 58.14 |
| CT | 100.00 | 23.26 |
| XRay | 80.00 | 18.60 |
The total is 430.00. The MRI claim with the blank amount contributes 0.
Dtypes after the transformation: claim_id string, procedure_group string, service_dt datetime64[ns], paid_amt float64, fiscal_month int64.
Why this is correct
- One source of truth. Group sums and the total both come from the same cleaned column, so they cannot disagree.
- Rounding last. Percentages are computed from exact sums. Note that the rounded percentages may not add to exactly 100.00 in general, which is acceptable for display.
- The modular formula is a bijection. It maps months 1 to 12 onto fiscal months 1 to 12 with October as the origin. Spot check: September gives (9 - 10) % 12 + 1 = 12.
- No NaN escapes. NaN exists only in the intermediate float and is replaced before the integer cast.
Showing vectorization
Nothing uses apply, iterrows, or a Python for loop over rows. dt.month, subtraction, %, addition, fillna, and astype all run as array operations. To demonstrate it, generate about a million random timestamps and time both versions with %timeit. The vectorized version typically takes tens of milliseconds, while an equivalent .apply(lambda d: ...) is often one to two orders of magnitude slower.
Complexity
- Time: O(n) for loading, cleaning and the fiscal-month computation, and O(n) for the hash-based groupby.
- Space: O(n) for the frame plus O(g) for g groups.
Common mistakes
- Trusting
parse_datesand ending up with anobjectcolumn after one bad value. - Dropping rows with missing amounts instead of treating them as 0, or dropping negative adjustments.
- Rounding group sums before computing percentages, which distorts the shares.
- Merging the total back to the rows and summing again, which double-counts.
- Using
.astype(int)on a column that still contains NaN, which raises an error. - Hard-coding a fix so that October returns 2, instead of raising the contradiction in the spec.
Edge cases worth mentioning
- A total of 0 (for example, adjustments cancel all charges): return NaN percentages rather than dividing by zero.
- Mixed or unexpected date formats: specify
format=if the format is known, and count theNaTresults so that data-quality issues are visible instead of silently mapped to 0. - Case or whitespace differences in group names (
"ct "versus"CT") split groups, so normalize them before aggregating. - Timezone-aware timestamps: decide whether the fiscal month should be based on local or UTC time before extracting the month.