Apply the function to the 0-dimension ndarray

Problem

  • I have ndarray, defined arr, which is an n-dimensional cube with a length min each dimension.

  • I want to use a function funcby slicing it to size n=0and taking each n-1-dim slice as an input to the function.

This seems to work for map(), but I cannot find a suitable option numpy. np.vectoriseseems to split the tag n-1into separate scalar entries. No apply_along_axis, no apply_over_axesdo not fit.

My problem is that I need to pass arbitrary functions as input, so I don't see a solution with einsumfeasible ones.

Question

  • Do you know a better numpyalternative to use np.asarray(map(func, arr))?

Example

I define an example array arrlike the 4-dim cube (or 4-tensor):

m, n = 3, 4 
arr = np.arange(m**n).reshape((m,)*n)

I define an example function f,

def f(x):
    """makes it obvious how the np.ndarray is being passed into the function"""
    try: # perform an op using x[0,0,0] which is expected to exist
        i = x[0,0,0]
    except:
        print '\nno element x[0,0,0] in x: \n{}'.format(x)
        return np.nan
    return x-x+i

The expected result,, resof this function will remain the same form, but will satisfy the following:

print all([(res[i] == i*m**(n-1)).all() for i in range(m)])

This works with a standard feature map(),

res = np.asarray(map(f, a))
print all([(res[i] == i*m**(n-1)).all() for i in range(m)])
True

I would expect it np.vectorizeto work the same as map()it does, but it acts in scalar entries:

res = np.vectorize(f)(a)

no element x[0,0,0] in x: 
0
...
+4
source share
1 answer

Given that arr- 4d, and yours fnworks on 3d arrays,

np.asarray(map(func, arr))

. ,

np.asarray([func(i) for i in arr])

for i in arr arr. arr . 4d-.

np.vectorize doc , . , . , np.vectorize . , , -

 [func(a,b) for a,b in zip(arrA, arrB)]

zip, . . func, .

np.vectorize np.frompyfunc, , . func.

np.apply_along/over_ax(e/i)s . , , .

, :

In [45]: res=np.zeros_like(arr,int)
In [46]: for i in range(arr.shape[0]):
    ...:     res[i,...] = f(arr[i,...])

, , .

, , .

========================

1- :

In [58]: arr.__array_interface__['data']  # data buffer address
Out[58]: (152720784, False)

In [59]: for i,a in enumerate(arr):
    ...:     print(a.__array_interface__['data'])
    ...:     a[0,0,:]=i
    ...:     
(152720784, False)   # address of the views (same buffer)
(152720892, False)
(152721000, False)

In [60]: arr
Out[60]: 
array([[[[ 0,  0,  0],
         [ 3,  4,  5],
         [ 6,  7,  8]],

        ...

       [[[ 1,  1,  1],
         [30, 31, 32],
         ...

       [[[ 2,  2,  2],
         [57, 58, 59],
         [60, 61, 62]],
       ...]]])

, , . , a[:]=..., . . a = ...., .

+1

All Articles