-1
rgb_list = []

int_list = [1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1]

for num in range(0, len(int_list)-3, 3):
    rgb_list.append(received_int[num:num+3])

received_array = np.array(rgb_list)
print(received_array)

received_array_2d = np.ndarray.reshape(received_array, (5, 2))
print(received_array_2d)

So up until received_array, everything was fine, but when I try to reshape it into a 2D array, I get an error code, I assume it's because numpy is considering each integer individually, not the arrays.

ValueError: cannot reshape array of size 30 into shape (5,2)

the output of print(received_array) is

[[1 0 0]
 [1 0 0]
 [1 1 0]
 [1 0 0]
 [1 1 1]
 [0 0 1]
 [0 1 0]
 [1 0 1]
 [0 1 0]
 [0 1 1]]

I want to get a 2D array that resembles this

[[1 0 0] [1 0 0] [1 1 0] [1 0 0] [1 1 1]
 [0 0 1] [0 1 0] [1 0 1] [0 1 0] [0 1 1]]

How would I go about doing that?

gabpas
  • 3
  • 4

1 Answers1

0

If you are using numpy arrays, use numpy methods: reshape is appropriate here.

You first need to trim your array to a multiple of the expected dimensions:

int_list = np.array([1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1])
X,Y,Z = 2,5,3
int_list[:X*Y*Z].reshape((2,5,3))

output:

array([[[1, 0, 0], [1, 0, 0], [1, 1, 0], [1, 0, 0], [1, 1, 1]],
       [[0, 0, 1], [0, 1, 0], [1, 0, 1], [0, 1, 0], [0, 1, 1]],
      ])
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Yup that's exactly what I wanted. Thanks a lot! Should I delete my question? It isn't well formulated, and I should've thought about it :( – gabpas Nov 29 '21 at 10:43