Numpy function to get the form of added arrays

tl; dr: How can I predict the form returned by multiple broadcasts on multiple arrays without actually adding arrays?

I have many scripts that use numpy broadcast rules (Python), so basically one-dimensional inputs lead to multi-dimensional output. As a basic example, the ideal gas law (pressure = rho * R_d *) may look like

def rhoIdeal(pressure,temperature): rho = np.zeros_like(pressure + temperature) rho += pressure / (287.05 * temperature) return rho 

This is not necessary here, but in more complex functions it is very useful to initialize an array with the correct shape. If pressure and temperature have the same shape, then rho also has this shape. If the pressure has the form (n,), and the temperature has the form (m,), I can call

 rhoIdeal(pressure[:,np.newaxis], temperature[np.newaxis,:]) 

to get rho with the form (n, m). This allows me to make graphs with several temperature values ​​without having to bend rhoIdeal , but it allows the script to take arrays of the same shape and calculate the result by elements.

My question is: is there a built-in function to return a form compatible with multiple inputs? Something that behaves like

 def returnShape(list_of_arrays): return np.zeros_like(sum(list_of_arrays)).shape 

without actually summing the arrays? If there is no built-in function, what would be a good implementation?

+4
source share
1 answer

You can use np.broadcast . This function returns an object that encapsulates the result of translating two or more arrays together. The actual operation (for example, adding) is not performed - the object simply has some of the same attributes as the array created using other operations (form, ndim, etc.).

For instance:

 x = np.array([1,2,3]) # shape (3,) y = x.reshape(3,1) # shape (3, 1) z = np.ones((5,1,1)) # shape (5, 1, 1) 

Then you can check what the shape of the array will be when you translate x , y and z by checking the shape attribute:

 >>> np.broadcast(x, y, z).shape (5, 3, 3) 

This means that you can implement your function as follows:

 def returnShape(*args): return np.broadcast(*args).shape 
+6
source

All Articles