python - Accessing array elements by internal data index and order -


this algorithmic problem bit complex me:

i have numpy array of data internally indexed in peculiar way. data output of 2 arrays spliced (which don't have), distinct ordering. set parameter max positive integer, , data output has index format

[ 00 10 20 ... max0 11 12 ... max1 22 23....max2 33....max max ] 

the parameter max determines output of array (i.e. length of array) , ordering.

for several examples, max=2, data of order

[00 10 20 11 21 22] 

setting max=3 gives

[00 10 20 30 11 21 31 22 32 33] 

and max=4

[00 10 20 30 40 11 21 31 41 22 32 42 33 43 44] 

and on.

i write algorithm make list/array of 3x values, i.e. values first index 3. is, access certain data values, organized first index.

however, determined parameter max. can see, determines datum placed array index. idea make sort of sorting tree, not sure how execute max parameter.

this list comprehension (or iteration) produces indexs show

[[j*10+i j in range(i,max+1)] in range(max+1)]  max=2: [[0, 10, 20], [11, 21], [22]] max=3: [[0, 10, 20, 30], [11, 21, 31], [22, 32], [33]] max=4: [[0, 10, 20, 30, 40], [11, 21, 31, 41], [22, 32, 42], [33, 43], [44]] 

these lists of lists can flattened. arrangement may make easier think problem.

or more useful generate tuples:

in [134]: [[(j,i) j in range(i,max+1)] in range(max+1)] out[134]:  [[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)],  [(1, 1), (2, 1), (3, 1), (4, 1)],  [(2, 2), (3, 2), (4, 2)],  [(3, 3), (4, 3)],  [(4, 4)]] 

it isn't clear want these numbers or indices, here's example of putting them in 2d array:

in [150]: dlist=[[j*10+i j in range(i,max+1)] in range(max+1)] in [151]: ilist=[[(j,i) j in range(i,max+1)] in range(max+1)]  in [152]: import itertools  in [155]: m=np.zeros((max+1,max+1),int) in [157]: (i,j),d in zip(itertools.chain(*ilist),itertools.chain(*dlist)):     m[i,j]=d  in [158]: m out[158]:  array([[ 0,  0,  0,  0,  0],        [10, 11,  0,  0,  0],        [20, 21, 22,  0,  0],        [30, 31, 32, 33,  0],        [40, 41, 42, 43, 44]]) 

the 1st 5 numbers go in 1st column, 2nd 4 in next, etc.

itertools.chain 1 way of flattening list of lists.

the layout of m looks lower-triangle. there's numpy function generate indices:

in [176]: np.tril_indices(5) out[176]:  (array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4], dtype=int32),  array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4], dtype=int32)) 

so have filled m with:

data =  np.dot([10,1],np.tril_indices(5)) m[np.tril_indices(5)] = data 

digging code of tril_indices find starting point mask of 1s generated by:

i=((np.arange(max)-np.arange(max)[:,none])<0).astype(int) array([[0, 0, 0, 0],        [1, 0, 0, 0],        [1, 1, 0, 0],        [1, 1, 1, 0]]) 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -