I have a list which contains 4 tuples. It is the output of multiprocessing.Pool.map()
, but I don't think that's important.
Each tuple contains 3 numpy arrays.
What is a good way to create 3 arrays, ie append (vstack) all the first arrays into 1, all the second into another, etc? Ie create the orange output from the orange arrays, etc, in the screenshot below:
I could of course do a very banal loop, like in the toy example below; it works, but it doesn't seem very elegant. I presume there's a more elegant/ pythonic way?
x = np.random.rand(10,2)
a = ((x,2*x,3*x))
b = a
c = a
d = a
my_list =[a,b,c,d]
num_items = len(my_list[0])
out =[None] * num_items
for i in range(num_items): #3 arrays in each tuple
out[i] =[]
for l in my_list:
out[i].append( l[i] )
out[i] = np.vstack(out[i])
my_array = np.array(my_list).swapaxes(0,1) # puts the `out` dimension in front
my_array.shape
Out[]: (3, 4, 10, 2)
if you want to concatenate the first dimension:
my.array.reshape(3, -1, 2) #-> shape (3, 40, 2)
if you really want a list:
list(my_array) #-> list of 3 arrays of shape (4, 10, 2)
You can try:
np.concatenate(my_list, axis=1)
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.