I have an index IDX
(which may be either list of indices, boolean mask, tuple of slices etc.) indexing some abstract numpy array of known shape shape
(possibly big).
I know I can create a dummy array, index it and count the elements:
A = np.zeros(shape)
print(A[IDX].size)
Is there any sensible way I can get the number of indexed elements without creating any (potentially big) array?
I need to tabularize a list of functions at certain points in 3D space. The points are subset of a rectangular grid given as X
, Y
, Z
lists and IDX
is indexing their Cartesian product:
XX, YY, ZZ = [A[IDX] for A in np.meshgrid(X, Y, Z)]
The functions accept either X
, Y
, Z
arguments (and return values for their Cartesian product which needs to be indexed) or XX
, YY
, ZZ
.
At the moment I create XX
, YY
and ZZ
arrays whether they are used or not, then I allocate an array for function values:
self.TAB = np.full((len(functions), XX.size),
np.nan)
but I want to create XX
, YY
and ZZ
only if they are necessary. I also want to separate TAB
allocation from filling its rows, thus I need to know the number of columns in advance.
Just for fun, let's see if we can make a passable approximation here. Your input can be any of the following:
If the input isn't explicitly a tuple to begin with, make it one. Now you can iterate along the tuple and match it to the shape. You can't quite zip them together because boolean arrays eat up multiple element of the shape, and trailing axes are included wholesale.
Something like this should do it:
This is only an approximation. You will need to change it any time the API changes, and it already has some incomplete features. Testing, fixing and, expanding is left as an exercise for the reader.