Home > Software design >  Correct use of np.reshape() command
Correct use of np.reshape() command

Time:11-15

I have a 1D-array which has the following structure:

arr = [x,a,b,c,y,a,b,c]

How can I convert that 1D array into a 3D-array like this:

arr2 = [[[x,a],[x,b],[x,c]], [[y,a], [y,b], [y,c]]] (3 y-values for each x-value)

CodePudding user response:

arr = np.array([1, 2, 2, 2, 3, 4, 4, 4, 5, 6, 6, 6])

arr = arr.reshape((3, -1))
arr = np.delete(arr, 0, 1)
print(arr)

Result:

[[2 2 2]
 [4 4 4]
 [6 6 6]]

After the OP's edit, this is the answer

arr = np.array([0, 7, 8, 9, 1, 7, 8, 9])

# Extract the component subarrays
sub_arr1 = arr[0:-1:4]   # every 4th element of arr
sub_arr2 = arr[1:4]      # the next 3 elements of arr, after skipping the first

m = np.array(np.meshgrid(sub_arr1, sub_arr2)).T
print(m)

Result:

[[[0 7]
  [0 8]
  [0 9]]

 [[1 7]
  [1 8]
  [1 9]]]

CodePudding user response:

arr = [1,2,3,4,5,6,7,8,9]
arr = np.array(arr)
arr = arr.reshape(3,3)
print (list(arr))
  • Related