Numpy ravel vs flat in slice assignment

According to the documentation, ndarray.flatiterates over the array, and ndarray.ravelreturns a flattened array (when possible). Therefore, my question is: when should we use this or that? Which one would be preferable as rvalue in assignment, for example, in the code below?

import numpy as np

x = np.arange(2).reshape((2,1,1))
y = np.arange(3).reshape((1,3,1))
z = np.arange(5).reshape((1,1,5))

mask = np.random.choice([True, False], size=(2,3,5))
# netCDF4 module wants this kind of boolean indexing:
nc4slice = tuple(mask.any(axis=axis) for axis in ((1,2),(2,0),(0,1)))
indices = np.ix_(*nc4slice)

ncrds = 3
npnts = (np.broadcast(*indices)).size
points = np.empty((npnts, ncrds))
for i,crd in enumerate(np.broadcast_arrays(x,y,z)):
    # Should we use ndarray.flat ...
    points[:,i] = crd[indices].flat
    # ... or ndarray.ravel():
    points[:,i] = crd[indices].ravel()
+4
source share
1 answer

You don’t need either. crd[mask]already 1st. If you did this, numpy always calls np.asarray(rhs), so this is the same if ravela copy is not required. When a copy is needed, I would suggest that it ravelmight be faster at the moment (I did not have time).

, , , , points . , , , , , ravel.

+4

All Articles