[Numpy-discussion] Iterate over all 1-dim views
Pauli Virtanen
ptvirtan at elisanet.fi
Sun Oct 7 08:40:46 EDT 2007
Neal Becker <ndbecker2 at gmail.com> kirjoitti:
> Suppose I have a function F(), which is defined for 1-dim arguments. If the
> user passes an n>1 dim array, I want to apply F to each 1-dim view.
>
> For example, for a 2-d array, apply F to each row and return a 2-d result.
>
> For a 3-d array, select each 2-d subarray and see above. Return 3-d result.
>
> Any suggestions on how to code something like this in numpy?
You may be looking for numpy.apply_along_axis:
>>> from numpy import *
>>> x=arange(2*3*4); x.shape=(2,3,4)
>>> x
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
>>> apply_along_axis(cumsum, 0, x)
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 14, 16, 18],
[20, 22, 24, 26],
[28, 30, 32, 34]]])
>>> apply_along_axis(cumsum, 1, x)
array([[[ 0, 1, 2, 3],
[ 4, 6, 8, 10],
[12, 15, 18, 21]],
[[12, 13, 14, 15],
[28, 30, 32, 34],
[48, 51, 54, 57]]])
>>> apply_along_axis(cumsum, 2, x)
array([[[ 0, 1, 3, 6],
[ 4, 9, 15, 22],
[ 8, 17, 27, 38]],
[[12, 25, 39, 54],
[16, 33, 51, 70],
[20, 41, 63, 86]]])
--
More information about the NumPy-Discussion
mailing list