[英]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.