Python 2.7: loop through 1D fibers in a multidimensional Numpy array

I am looking for a way to loop over 1D fibers (rows, columns and multidimensional equivalents) over any dimension in a 3+ dimensional array. In a 2D array, this is pretty trivial since the fibers are rows and columns, so they just say that “for a row in A” does its job. But, for example, 3D arrays, this expression is repeated over two-dimensional slices, and not 1D fibers. A working solution is below, but I wonder if there is something A) more idiomatic B) faster.

import numpy as np
A = np.arange(27).reshape((3,3,3))
func = np.sum
for fiber_index in np.ndindex(A.shape[:-1]):
    print func(A[fiber_index])

Hope you can help!

+4
source share
2 answers

I think you can search numpy.apply_along_axis

In [10]: def my_func(x):
   ...:     return x**2 + x

In [11]: np.apply_along_axis(my_func, 2, A)
Out[11]: 
array([[[  0,   2,   6],
        [ 12,  20,  30],
        [ 42,  56,  72]],

       [[ 90, 110, 132],
        [156, 182, 210],
        [240, 272, 306]],

       [[342, 380, 420],
        [462, 506, 552],
        [600, 650, 702]]])

NumPy ( sum) axis, , :

In [12]: np.sum(A, axis=2)
Out[12]: 
array([[ 3, 12, 21],
       [30, 39, 48],
       [57, 66, 75]])
+2

numpy 1 .

:

func = np.sum
for fiber_index in np.ndindex(A.shape[:-1]):
    print func(fiber_index)
    print A[fiber_index]

- :

(0, 0)
[0 1 2]
(0, 1)
[3 4 5]
(0, 2)
[6 7 8]
...

1- 2- , 1D- .

ndindex. . fooobar.com/questions/533771/....

as_strided , nditer. "multi_index" , . __next__. , numpy .

http://docs.scipy.org/doc/numpy-dev/reference/arrays.nditer.html Iterating Over Arrays , cython.

, sum, max, product, , () . , sum, :

np.sum(A, axis=-1)
np.sum(A, axis=(1,2))   # sum over 2 axes

np.add.reduce(A, axis=-1)

np.add ufunc, reduce . ufunc - accumulate, reduceat. ufunc.

xnx

np.apply_along_axis(np.sum, 2, A)

apply_along_axis, , A. i, j while, :

outarr[(i,j)] = np.sum(A[(i, j, slice(None))])

slice - . , , . , .


. "" , .

def with_ndindex(A, func, ax=-1):
    # apply func along axis ax
    A = np.rollaxis(A, ax, A.ndim) # roll ax to end (changes strides)
    shape = A.shape[:-1]
    B = np.empty(shape,dtype=A.dtype)
    for ii in np.ndindex(shape):
        B[ii] = func(A[ii])
    return B

3x3x3, 10x10x10 100x100x100 A. np.ndindex , apply_along_axis. np.sum(A, -1) .

, func 1D- ( sum), ndindex .

+2

All Articles