Home > Back-end >  Create 4d numpy array from lists, where axis[i] holds the list[i] elements
Create 4d numpy array from lists, where axis[i] holds the list[i] elements

Time:03-11

I have three lists, and I can build a numpy array of objects with (3,2,4) shape from them.

However, what I want is a numpy array with shape (2, 3, 4), where each axis corresponds to a "variable" in the list. I tried using np.reshape with no success.

import numpy as np
p1 = [[1, 1, 1, 1], [1, 1, 1, 1]]
p2 = [[0, 0, 0, 0], [0, 0, 0, 0]]
p3 = [[2, 2, 2, 2], [2, 2, 2, 2]]
points = [p1, p2, p3]
nparr = np.array(points, dtype=np.float32)

What I obtain is

[[[1. 1. 1. 1.]
  [1. 1. 1. 1.]]

 [[0. 0. 0. 0.]
  [0. 0. 0. 0.]]

 [[2. 2. 2. 2.]
  [2. 2. 2. 2.]]]

But what I would like to obtain is

[[[1. 1. 1. 1.]
  [0. 0. 0. 0.]
  [2. 2. 2. 2.]]  

[[[1. 1. 1. 1.]
  [0. 0. 0. 0.]
  [2. 2. 2. 2.]] 

Is there a clean way to achieve this without having to change the original input lists?

CodePudding user response:

nparr = np.array([a for a in zip(p1,p2,p3)], dtype=np.float32)

or

nparr = np.squeeze(np.array([list(zip(p1,p2,p3))]), dtype=np.float32)

CodePudding user response:

You can just do a transposition of the two first axis using:

nparr.transpose(1, 0, 2)

Since transpose return a view of the array with modified strides, this operation is very very cheap. However, on big array, it may be better to copy the view using .copy() so to work on contiguous views.

  • Related