简体   繁体   中英

convert chunks of numpy array to tuple

I have a numpy array like this

array([[243],
       [243],
       [243],
       [243],
       [243],
       [243],
       [243],
       [245],
       [244],
       [244],
       [244],
       [243],

and every three element from it will be converted into a tuple! I have written a simple generator like this,

def RGBchunks(a_list):
    for i in range(0,len(a_list),3):
        temp = []
        for j in range(3):
            temp.extend(a_list[i+j])
        yield tuple(temp)

Which gives what I wanted, like this,

>>> for i in RGBchunks(my_arr):
         print(i)


(243, 243, 243)
(243, 243, 243)
(243, 243, 243)
(244, 244, 244)
(245, 245, 245)
(244, ........
..............
(243, 243, 243)

I'm curious as to know whether is there some simple elegant way to do this in numpy! And probably all those tuples in a new list? any Pythonic way is I'm curious. performance increasing would be very good too!

If it's a simple reshape operation without any overlaps, use reshape :

my_arr.reshape(-1, 3)

Or,

np.reshape(my_arr, (-1, 3))

array([[243, 243, 243],
       [243, 243, 243],
       [243, 245, 244],
       [244, 244, 243]])

If you really want a list of tuples, call map on the reshaped result:

list(map(tuple, my_arr.reshape(-1, 3)))

Or, with a list comprehension for performance:

[tuple(x) for x in my_arr.reshape(-1, 3)]

[(243, 243, 243), (243, 243, 243), (243, 245, 244), (244, 244, 243)]

For overlapping strides, there's stride_tricks :

f = np.lib.stride_tricks.as_strided
n = 3

f(my_arr, shape=(my_arr.shape[0] - (n + 1), n), strides=my_arr.strides)

array([[243, 243, 243],
       [243, 243, 243],
       [243, 243, 243],
       [243, 243, 243],
       [243, 243, 243],
       [243, 243, 245],
       [243, 245, 244],
       [245, 244, 244],
       [244, 244, 244],
       [244, 244, 243]])

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