简体   繁体   中英

1D to 2D array - python

I would like to change the data stored in 1D into 2D: I mean:

from

x|y|a
1|1|a(1,1)
2|1|a(2,1)
3|1|a(3,1)
1|2|a(1,2)
...

into:

x\y|1     |2     |3
1  |a(1,1)|a(1,2)|a(1,3
2  |a(2,1)|a(2,2)|a(2,3)...
3  |a(3,1)|a(3,2)|a(3,3)...
    ...

I did it by 2 loops:

(rows - array of x,y,a)
for n in range(len(rows)):
            for k in range(x_len):
                    for l in range(y_len):
                            if ((a[2, n] == x[0, k]) and (a[3, n] == y[0, l])):
                                    c[k, l] = a[0, n]

but it takes ages, so my question is if there is a smart and quick solution for that in Python.

So to clarify what I want to do:

I know the return() function, the point is that it's randomly in array a .

So:

 a = np.empty([4, len(rows)] 

I read the data into array a from the database which has 4 columns (1,2,x,y) and 'len(rows)' rows .

I am interested in '1' column - this one I want to put to the new modified array.

 x = np.zeros([1, x_len], float) y = np.zeros([1, y_len], float) 

x is a vector of sorted column(x) from the array a , but without duplicitas with a length x_len

(I read it by the sql query: select distinct ... )

y is a vector of sorted column(y) from the array a (without duplicitas) with a length y_len

Then I am making the array:

 c = np.zeros([x_len, y_len], float) 

and put by 3 loops (sorry for the mistake before) the data from array a: >

  for n in range(len(rows)): for k in range(x_len): for l in range(y_len): if ((a[2, n] == x[0, k]) and (a[3, n] == y[0, l])): c[k, l] = a[0, n] 

Example:

Array a

  array([[1, 3, 6, 5, 6], [1, 2, 5, 5, 6], [1, 4, 7, 1, 2], ## x [2, 5, 3, 3, 4]]) ## y 

Vectors: x and y

  [[1,2,4,7]] ## x with x_len=4 [[2,3,4,5]] ## y with y_len=4 

Array c

  array([[1, 5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 3], [0, 6, 0, 0]]) 

the last array c looks like this (the first a[0] is written into):

  x\\y 2|3|4|5 ----------- 1 1|5|0|0 2 0|0|0|0 4 0|0|0|3 7 0|6|0|0 

I hope I didn't make mistake how it's written into the array c .

Thanks a lot for any help.

You could use numpy:

>>> import numpy as np
>>> a = np.arange(9)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> a.reshape(3,3)
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
#or:
>>> a.reshape(3,3).transpose()
array([[0, 3, 6],
       [1, 4, 7],
       [2, 5, 8]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM