numpy / numpy/numpy

np.average lacks of proper error message and docs when weights is 1D and axis is a tuple

Open
#10,989 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
32.8k
Forks
12.8k
Avg merge
1d 7h
Merged PRs (30d)
197

Description

Since version 1.7.0, the axis in np.average could be a tuple of ints. However, when weights is a 1-D array and axis is a tuple, this line of code will raise a TypeError

>>> data = np.arange(6).reshape((3, 2))
>>> data
array([[0, 1],
       [2, 3],
       [4, 5]])
>>> np.average(data, weights=[3, 1], axis=(0, 1))

   1145                 raise TypeError(
   1146                     "1D weights expected when shapes of a and weights differ.")
-> 1147             if wgt.shape[0] != a.shape[axis]:
   1148                 raise ValueError(
   1149                     "Length of weights not compatible with specified axis.")

TypeError: tuple indices must be integers or slices, not tuple

I think we should check whether the axis is a int when weights is a 1-D array and raise a TypeError like this:
TypeError: Axis must be a single int, not a tuple when shapes of a and weights differ.

And the doc about axis should be updated with something like this:

NOTE: The axis can be a tuple of ints only when weights has the same shape with the input array.

Can I create a PR to fix this?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the provided example and inspect the linked axis-handling code in numpy/lib/function_base.py. Update the behavior and the axis documentation so the tuple case with 1-D weights is clearly handled, then rerun the example to confirm the resulting error and documentation match the issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
data
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.