Thanks to visit codestin.com
Credit goes to github.com

Skip to content

np.clip broadcasts input array to fit a_min/a_max #8471

Closed
@befelix

Description

@befelix

np.clip allows to clip multi-dimensional arrays by taking arrays for a_min and a_max. However, when providing bounds that are array-likes that don't match the source sometimes one can weird results.
For example, while

a = np.arange(5)
a.clip([0, 0], [1, 1])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-23-ad92301a6712> in <module>()
      1 a = np.arange(5)
----> 2 a.clip([0, 0], [2, 2])

ValueError: operands could not be broadcast together with shapes (5,) (2,)

raises an error as expected, the following passes:

a = np.arange(5)[:, None]
a.clip([0, 0], [2, 2])

array([[0, 0],
       [1, 1],
       [2, 2],
       [2, 2],
       [2, 2]])

I guess what's happening is that the input array is broadcasted to fit the constraints. Is this expected? I would have expected an error to be raised instead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions