Skip to content

Commit

Permalink
Merge pull request #26 from ONSBigData/i21/zero-division-bug-aggregation
Browse files Browse the repository at this point in the history
Handle all invalid indices in aggregate/weight_shares functions
  • Loading branch information
mitches-got-glitches authored Dec 1, 2020
2 parents 865ef34 + a1db3f8 commit 4e441a7
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
14 changes: 10 additions & 4 deletions precon/aggregation.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from pandas._typing import Axis, FrameOrSeriesUnion

from precon.weights import get_weight_shares, reindex_weights_to_indices
from precon.helpers import flip
from precon.helpers import flip, axis_slice
from precon._validation import _handle_axis


Expand Down Expand Up @@ -64,10 +64,16 @@ def aggregate(
# axis before aggregating.
weights = reindex_weights_to_indices(weights, indices, flip(axis))

# Ensure zero or NA indices have zero weight
weights = weights.mask(indices.isna() | indices.eq(0), 0)
# Ensure zero, NA and inf indices have zero weight so weight shares
# calculation reflects the indices being excluded.
zero_weights_mask = indices.isin([0, np.nan, np.inf])
masked_weights = weights.mask(zero_weights_mask, 0)

weight_shares = get_weight_shares(weights, axis)
# Except where all indices are zero, NA and inf.
slice_ = axis_slice(zero_weights_mask.all(axis), flip(axis))
masked_weights.loc[slice_] = np.nan

weight_shares = get_weight_shares(masked_weights, axis)
return agg_method(indices, weight_shares, axis)


Expand Down
2 changes: 1 addition & 1 deletion precon/weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def get_weight_shares(
axis = _handle_axis(axis)
# TODO: test precision
if not weights.sum(axis).round(5).eq(1).all():
return weights.div(weights.sum(axis), axis=flip(axis))
return weights.div(weights.sum(axis, min_count=1), axis=flip(axis))

else: # It is already weight shares so return input
return weights
Expand Down

0 comments on commit 4e441a7

Please sign in to comment.