# [Tutor] 1d to 2d array creation

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Oct 2 00:27:39 CEST 2012

```On 1 October 2012 22:04, Bala subramanian <bala.biophysics at gmail.com> wrote:

> Friends,
> I have an 1d array like a=[1, 1, 2, 2, 2, 3, 3, 1, 1, 1], i have to
> convert it to 2d array for plotting as follows. The 2d array is filled
> by a[colum index] to obtain the new array shown below.
>
> [ [ 1.,  1.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,  1.],
>   [ 0.,  0.,  2.,  2.,  2.,  0.,  0.,  0.,  0.,  0.],
>   [ 0.,  0.,  0.,  0.,  0.,  3.,  3.,  0.,  0.,  0.] ]
>
> I wrote the following simple code for the conversion. However i guess
> there should be more fancy/speeder way to do that. Also i need to
> create such 2d-array from larger 1d arrays of size 20000,30000 items
> etc. Hence i would like to request hints for a better code for the
> purpose.
>
> Here no. rows in my case is always = no. of discrete values in array a.
>
> >>>my=1
> >>>for i in range(3):
> >>>      for j in range(10):
> >>>             if a[j] == my : b[i,j]=my
> >>>             else: b[i,j]=0
> >>>      my +=1
>

my = 1
for i in range(3):
# stuff
my += 1

why not do

for my in range(1, 4):
# stuff

But actually it makes more sense to eliminate one of the loops and do:

for i, ai in enumerate(a):
b[i, ai] = ai

It may be that you get better speed with something like

for j in range(max(a.max)):
b[j, a==j+1] = j

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20121001/313a11d9/attachment.html>
```