Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new numpy array from existing array efficiently

I have existing numpy array (uint8) which looks like this:

(Values are 8bit, i am interested only in last 3 of them)

[
    [ 00000AAA, 00000BBB, 00000CCC ],
    [ 00000FFF, 00000EEE, 00000DDD ],
    [ 00000GGG, 00000HHH, 00000III ],
    [ 00000LLL, 00000KKK, 00000JJJ ]
]

And in the end I would like to have data in this form:

[01AAABBB, 01CCCDDD 01EEEFFF, 01GGGHHH, 01IIIJJJ, 01KKKLLL]

Also, every second row is reversed.

Currently i have a long and winding code whitch iterates over the original list row-by-row and cell-by-cell, shifts and adds data, but that is not efficient enough.

Are there any good and efficinet methods solving that problem?

like image 921
zidik Avatar asked Sep 25 '26 05:09

zidik


1 Answers

Here's an approach using Numpy built-in commands and vector style indexing, so it's pretty compact (and should be quicker than iterating):

Updated with suggestions from comments

# Reverse direction of every second row
unsnaked_array       = np.array(inp_array)
unsnaked_array[1::2] = inp_array[1::2, ::-1]

# Change to one long array
unsnaked_array = unsnaked_array.ravel()
unsnaked_array &= 0x7    # Extra safety :)    

# Sum every pair of elements (with first element rolled) and add required bit
result_array = (unsnaked_array[::2]<<3) + unsnaked_array[1::2] + (1<<6)
like image 94
Pokey McPokerson Avatar answered Sep 26 '26 17:09

Pokey McPokerson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!