Test if an array is broadcastable to a shape?

后端 未结 5 1852
灰色年华
灰色年华 2021-01-21 16:39

What is the best way to test whether an array can be broadcast to a given shape?

The \"pythonic\" approach of trying doesn\'t work for my case, because the

5条回答
  •  别那么骄傲
    2021-01-21 17:15

    For the case of when you want to check any number of array-like objects (opposed to passing shapes), we can leverage np.nditer for broadcasting array iteration.

    def is_broadcastable(*arrays):
        try:
            np.nditer(arrays)
            return True
        except ValueError:
            return False
    

    Be aware that this only works for np.ndarray or classes that define __array__ (which will be called).

提交回复
热议问题