To divide each NumPy row by its own sum, compute counts.sum(axis=1, keepdims=True) and divide the original array by those totals. For a two-dimensional count table, keepdims=True gives you a column of denominators that broadcasts across the categories in each row. Use np.divide with an initialized output and a mask when a row can have a total of zero.
Consider a table with stores as rows and sales channels as columns. Row normalization answers what share of each store’s sales came through each channel. The calculation is short, but a misplaced axis can assign denominators to the wrong values and still produce a result with the expected shape.
Choose the axis that defines the total
Start with the question the share should answer. For a table shaped (stores, channels), a store’s channel share uses that store’s total across all channels. Summing along axis=1 collapses the channel dimension. Summing along axis=0 collapses the store dimension and gives each channel’s total across stores. A sum over the entire array gives one denominator for every cell. Each calculation describes a different population.
With a two-dimensional table, keeping the reduced dimension in place makes the intended denominator easy to read from its shape.
| Denominator | Expression | Result shape |
|---|---|---|
| One total per store | counts.sum(axis=1, keepdims=True) | (stores, 1) |
| One total per channel | counts.sum(axis=0, keepdims=True) | (1, channels) |
| One total for the whole table | counts.sum() | Scalar |
For row shares, NumPy matches the store dimension of (stores, channels) and (stores, 1). It then uses the denominator from each store at every channel position in that store’s row. The division produces one output value per input cell. Broadcasting handles the repeated use of each total, so the denominator array can stay at one value per store.
Check the labels before choosing the axis if the array came from a pivot or transpose. Once a table becomes an ordinary NumPy array, the calculation sees dimension positions. If channels occupy the first dimension, summing along axis=0 produces a total for each store.
Check how NumPy aligns the denominator
Without keepdims, a row reduction returns a one-dimensional array. NumPy compares the trailing dimensions first, so a vector of length two lines up with the two columns of a square table. Consider these sample counts.
import numpy as np
counts = np.array([[1, 3],
[2, 8]])
totals = counts.sum(axis=1) # [4, 10], shape (2,)
counts / totals
# array([[0.25, 0.30],
# [0.50, 0.80]])
counts / counts.sum(axis=1, keepdims=True)
# array([[0.25, 0.75],
# [0.20, 0.80]])In the first division, NumPy uses 4 for every value in the first column and 10 for every value in the second. The first row therefore sums to 0.55. In the second division, both first-row values use 4, and both second-row values use 10. Both rows then sum to one.
The same mistake can also change the result’s shape. A table with two rows and one column has shape (2, 1). Its flattened row totals have shape (2,). When NumPy combines those arrays, it treats the vector as having shape (1, 2) for alignment, producing a (2, 2) result. Each original count is divided by both totals.
If you already have a one-dimensional array containing one total per row, totals[:, None] inserts the required length-one dimension. When the totals are computed in the same expression or function, keepdims=True keeps the dimension in its original position and works just as well for arrays with additional leading dimensions.
Handle zero-total rows explicitly
For nonnegative counts, a zero total means every category count in the row is zero. That row has no observed composition. A chart that needs a fixed shape can use zeros as a display convention. A downstream calculation that treats missing composition differently from an observed share of zero can use NaN or retain a separate mask. Choose the convention before any averaging or filtering uses the normalized values.
The function below accepts real, finite, nonnegative counts and normalizes along the final axis. It represents zero-total rows with zeros. Converting to float64 before the sum gives the output room for fractions and puts the reduction on floating-point arithmetic. An overflowing sum raises an error.
def row_shares(values):
counts = np.asarray(values, dtype=np.float64)
if counts.ndim == 0 or counts.shape[-1] == 0:
raise ValueError("Expected a nonempty category axis")
if not np.isfinite(counts).all() or (counts < 0).any():
raise ValueError("Counts must be finite and nonnegative")
with np.errstate(over="raise"):
totals = counts.sum(axis=-1, keepdims=True)
shares = np.zeros_like(counts)
np.divide(counts, totals, out=shares, where=totals > 0)
return sharesThe mask has the same shape as the totals, so it broadcasts across the categories. Positive-total rows are divided normally. Where the mask is false, np.divide leaves the corresponding values in shares alone. Passing the initialized out array makes those entries predictable. For a missing-value convention, initialize it with np.full_like(counts, np.nan) instead.
A mask applied after division comes too late to prevent division by zero. The same issue applies to np.where(totals > 0, counts / totals, 0) because Python evaluates the division before calling np.where. The where argument to np.divide controls where the division itself takes place.
Missing counts and signed values need their own interpretation. A missing count might mean a channel failed to report. Signed counts can cancel to zero even when the row contains activity. The input checks keep either situation from being assigned the same meaning as a row of observed zeros.
Normalize batches of count tables
For a stack of daily tables shaped (days, stores, channels), axis=-1 still selects the channel dimension. The totals have shape (days, stores, 1), so each store gets a separate denominator for each day. The same function works on a single table shaped (stores, channels) or on a single store’s vector of channel counts. In every case, the last dimension is the category axis.
daily = np.array([
[[2, 6], [0, 0]], # Day 1
[[3, 1], [1, 1]], # Day 2
])
daily_shares = row_shares(daily)
pooled_shares = row_shares(daily.sum(axis=0))For the first store, the first channel accounts for 2/8 on day one and 3/4 on day two. Averaging the two daily shares gives 1/2, with each day contributing equally. Pooling counts first gives 5/12, the share of that channel across all recorded sales. The daily table is useful for tracking changes in channel mix. The pooled table describes the mix over the full period.
The distinction matters for the second store, which recorded zero sales on day one. Including that day’s zero-filled row in a mean lowers the resulting shares. If the question is about a typical day with recorded sales, average only the days with positive totals for that store. If the question is about all sales over the period, sum the counts across days first and normalize once.
Verify the result with small fixtures
Use a rectangular example with different positive row totals and a zero-total row. Check the output shape, check some known fractions, and verify that the row sums follow your zero-total policy. These checks cover different mistakes. A shape check catches accidental expansion, while a known fraction can reveal a denominator from the wrong row even when the shape happens to match.
sample = np.array([[2, 6, 0],
[0, 0, 0],
[1, 1, 2],
[0, 3, 0]])
shares = row_shares(sample)
assert shares.shape == sample.shape
np.testing.assert_allclose(shares[0], [0.25, 0.75, 0.0])
np.testing.assert_allclose(shares.sum(axis=-1), [1.0, 0.0, 1.0, 1.0])
np.testing.assert_allclose(row_shares([[7], [0]]), [[1.0], [0.0]])The final check covers tables with one category, where an omitted dimension can silently expand the output. A positive count in the sole category should produce a share of one, and the zero count should follow the configured zero-total policy. If square inputs occur in the actual workflow, retain a fixture with unequal row totals there too. The incorrect division in the earlier square example passes a shape check.
Compare floating-point shares with a tolerance. For example, repeated fractions such as one third can accumulate rounding error when you sum them. Keep full precision through the analysis and apply display rounding at the point where the table or chart is rendered. That keeps formatting decisions out of downstream calculations.
Frequently Asked Questions
Does the original count array change?
The function writes to a separate output array created by np.zeros_like. The source counts remain available for pooled totals, weighting, or auditing the zero-total rows.
Can a boolean array be normalized this way?
Yes. The conversion to float64 turns True into one and False into zero. Each true entry receives an equal share of the row’s true entries, and an all-false row follows the zero-total policy.
What if the category axis is in the middle of the array?
Use its axis number for the reduction and keep that dimension with keepdims=True. For the function shown here, you can move the category axis to the last position with np.moveaxis, normalize, then move it back.
Should a filtered set of channels still sum to one?
Filter before normalization if the shares should describe the selected channels alone. Filter after normalization if the shares should retain their original meaning as fractions of all channels. In the second case, the visible shares may sum to less than one.




