# [Numpy-discussion] converting 1 dimensional array to 2 dimensional array

Juan Nunez-Iglesias jni at fastmail.com
Mon Jul 15 14:13:48 EDT 2019

```Hi Omry!

You're looking for `.view()`:

In [1]: import numpy as np
In [2]: b = np.arange(1, 13).astype(np.uint8)
In [4]: y = b.view(np.uint16).reshape((3, 2))
In [5]: y
Out[5]:
array([[ 513, 1027],
[1541, 2055],
[2569, 3083]], dtype=uint16)

You can also change the endianness by replacing `np.uint16` with `'>u2'`.

In [6]: z = b.view('>u2')
In [7]: z
Out[7]: array([ 258, 772, 1286, 1800, 2314, 2828], dtype=uint16)

Hope this helps!

Juan.

On Mon, 15 Jul 2019, at 12:45 PM, Omry Levy wrote:
> Hi All,
>
> I know how to reshape arrays, my problem is a little more complicated than that.
> I am looking for the most efficient way to do the following and an example will help:
>
> 1) I have a an array of bytes b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
> This bytes array represents a width of 2 and a height of 3.
> Each 2 bytes in that bytes array makes an unsigned 16 bit integer.
>
> 2) I want to get the following 2 dimensional array from the bytes array where each item in the two dimensional array is an unsigned 16 bit integer
> something like:
>
> [
>  [(1,2) , (3,4)],
>  [(5,6) , (7,8)],
>  [(9,10) , (11,12)]
> ]
>
> in the first row there are 2 elements each one is made of 2 bytes from the bytes array etc...
> meaning that
> (1, 2) = b[0] + b[1] << 8
> (3, 4) = b[2] + b[3] << 8
> ...
> ...
>
> What is the most efficient way to achieve that with numpy ?
> Thanks
> 0L
>
>
>
>
>
>
> [1] << 8 ,[2], [3, 4]
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at python.org
> https://mail.python.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20190715/1c573c32/attachment.html>
```