Sum Each Column of a 2-D NumPy Array Without a Loop
Quick Overview
Sum every column of a 2-D NumPy array without any Python loop. It tests reductions along an axis, the shape and dtype of the result, and how keepdims changes broadcasting when the reduced values are combined with the original array.
Sum Each Column of a 2-D NumPy Array Without a Loop
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 2-D array of shape `(rows, cols)`, return a 1-D array of length `cols` where entry `i` is the sum of column `i`. Reduce along `axis=0`, and do not use a Python `for` loop, a list comprehension, or any other manual iteration.
For example:
```python
a = np.array([[1, 2, 3],
[4, 5, 6]])
column_sums(a) # -> array([5, 7, 9])
```
```hint Count the outputs
The result needs one entry per column. Work out which axis the reduction has to remove to leave exactly that shape.
```
### What a Strong Answer Covers
- The reduction call and the axis it collapses.
- The shape of the result, checked against the example.
- Why the vectorized call is faster than a Python loop.
- The dtype of the result and edge cases such as `NaN` values or an array with zero rows.
### Follow-up Questions
- What changes if you use `axis=1` instead?
- How would you keep the result 2-D for broadcasting, and when does that matter?
- What dtype does the result have for an `int8` or boolean input, and when can the sum still overflow?
Overview: Sum every column of a 2-D NumPy array without any Python loop. It tests reductions along an axis, the shape and dtype of the result, and how keepdims changes broadcasting when the reduced values are combined with the original array.
Given a 2-D array of shape (rows, cols), return a 1-D array of length cols where entry i is the sum of column i. Reduce along axis=0, and do not use a Python for loop, a list comprehension, or any other manual iteration.