[英]numpy ravel versus flat in slice assignment
根据文档, ndarray.flat
是数组上的迭代器,而ndarray.ravel
返回一个flattened数组(如果可能)。 所以我的问题是,我们应该何时使用其中一种? 哪一个更适合作为赋值中的右值,如下面的代码中的rvalue?
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()
你也不需要。 crd[mask]
已经是1-d了。 如果你没有,numpy的总是调用np.asarray(rhs)
第一,所以它是相同的,如果需要对没有复制ravel
。 当需要副本时,我猜想目前的ravel
可能更快(我没有时间)。
如果你知道,可能需要一个副本,在这里你知道这是什么都不需要,重塑points
实际上可能是最快的。 既然你通常不需要最快,我会说它更多的是品味,并且个人可能会使用ravel
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.