Numpy, python: automatically expand dimensions of arrays when broadcasting

后端 未结 2 919
再見小時候
再見小時候 2021-02-19 21:36

Consider the following exercise in Numpy array broadcasting.

import numpy as np
v = np.array([[1.0, 2.0]]).T # column array

A2 = np.random.randn(2,10) # 2D arra         


        
2条回答
  •  离开以前
    2021-02-19 21:56

    NumPy broadcasting adds additional axes on the left.

    So if you arrange your arrays so the shared axes are on the right and the broadcastable axes are on the left, then you can use broadcasting with no problem:

    import numpy as np
    v = np.array([[1.0, 2.0]])  # shape (1, 2)
    
    A2 = np.random.randn(10,2) # shape (10, 2)
    A3 = np.random.randn(10,10,2) # shape (10, 10, 2)
    
    v * A2  # shape (10, 2)
    
    v * A3 # shape (10, 10, 2)
    

提交回复
热议问题