python - numpy ravel versus flat in slice assignment -
according documentation, ndarray.flat iterator on array while ndarray.ravel returns flattened array (when possible). question is, when should use 1 or other? 1 preferred rvalue in assignment 1 in code below?
import numpy 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 kind of boolean indexing: nc4slice = tuple(mask.any(axis=axis) axis in ((1,2),(2,0),(0,1))) indices = np.ix_(*nc4slice) ncrds = 3 npnts = (np.broadcast(*indices)).size points = np.empty((npnts, ncrds)) i,crd in enumerate(np.broadcast_arrays(x,y,z)): # should use ndarray.flat ... points[:,i] = crd[indices].flat # ... or ndarray.ravel(): points[:,i] = crd[indices].ravel()
you don't need either. crd[mask] 1-d. if did, numpy calls np.asarray(rhs) first, same if no copy needed ravel. when copy needed, guess ravel may faster (i did not time it).
if knew copy might needed, , here know nothing needed, reshaping points fastest. since don't need fastest, more matter of taste, , use ravel.
Comments
Post a Comment