Test if an array is broadcastable to a shape?

后端 未结 5 1850
灰色年华
灰色年华 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:03

    You could use np.broadcast. For example:

    In [47]: x = np.ones([2,2,2])
    
    In [48]: y = np.ones([2,3])
    
    In [49]: try:
       ....:     b = np.broadcast(x, y)
       ....:     print "Result has shape", b.shape
       ....: except ValueError:
       ....:     print "Not compatible for broadcasting"
       ....:     
    Not compatible for broadcasting
    
    In [50]: y = np.ones([2,2])
    
    In [51]: try:
       ....:     b = np.broadcast(x, y)
       ....:     print "Result has shape", b.shape
       ....: except ValueError:
       ....:     print "Not compatible for broadcasting"
       ....:
    Result has shape (2, 2, 2)
    

    For your implementation of lazy evaluation, you might also find np.broadcast_arrays useful.

提交回复
热议问题