[Numpy-discussion] Flattening an array

Charles R Harris charlesr.harris@gmail....
Wed Dec 9 23:59:22 CST 2009

On Tue, Dec 8, 2009 at 5:29 PM, Jake VanderPlas <jakevdp@gmail.com> wrote:

> Hello,
> I have a function -- call it f() -- which takes a length-N 1D numpy
> array as an argument, and returns a length-N 1D array.
> I want to pass it the data in an N-D array, and obtain the N-D array
> of the result.
> I've thought about wrapping it as such:
> #python code:
> from my_module import f   # takes a 1D array, raises an exception otherwise
> def f_wrap(A):
>    A_1D = A.ravel()
>    B = f(A_1D)
>    return B.reshape(A.shape)
> #end code
If the function treats both types of input the same and the input arrays are
genuinely C/F contiguous, then you can just reshape them

A_1D = A.reshape(-1, order='C') # c order
A_1D = A.reshape(-1, order='F') # fortran order

Warning: if they aren't contiguous of the proper sort, copies will be made.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20091209/f9f88911/attachment.html 

More information about the NumPy-Discussion mailing list