简体   繁体   English

我无法在不修改它们的情况下重塑大小为 3 的 np arrays 的一维 np 数组

[英]I'm unable to reshape a 1D np array of np arrays of size 3 without modifying them

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.所以直到 received_array,一切都很好,但是当我尝试将其重塑为二维数组时,我收到一个错误代码,我认为这是因为 numpy 正在单独考虑每个 integer,而不是 ZA3CBC3F9D6CE2F2C1D9CZE。

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

the output of print(received_array) is print(received_array)的 output 是

[[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?我将如何 go 这样做?

If you are using numpy arrays, use numpy methods: reshape is appropriate here.如果您使用的是 numpy arrays,请使用 numpy 方法:此处适合reshape

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: 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]],
      ])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM