python - 无法 reshape numpy 数组

标签 python numpy multidimensional-array reshape

我有一个函数应该采用一维整数数组并将其整形为 1x3 数组的二维数组。然后它应该获取每个 1x3 数组并将其转换为 3x1 数组。结果应该是 3x1 数组的二维数组。这是我的功能

def RGBtoLMS(rgbValues, rgbLength): #Method to convert from RGB to LMS
    print rgbValues
    lmsValues = rgbValues.reshape(-1, 3)
    print lmsValues
    for i in xrange(len(lmsValues)):
        lmsValues[i] = lmsValues[i].reshape(3, 1)

    return lmsValues

当我尝试将 1x3 数组更改为 3x1 数组时,问题出现了。我得到以下输出假设 rgbValues = [14, 25, 19, 24, 25, 28, 58, 87, 43]

[14 25 19 ..., 58 87 43]
[[14 25 19]
 [24, 25, 28]
 [58 87 43]]

ValueError [on line lmsValues[i] = lmsValues[i].reshape(3, 1)]: could not broadcast input array from shape (3,1) into shape (3)

我怎样才能避免这个错误?

最佳答案

如评论中所述,您实际上总是只是修改一个具有不同形状的数组。在 numpy 中说你有一个 1 x 3 数组的二维数组并没有什么意义。这实际上是一个 n x 3 数组。

我们从长度为 3*n 的一维数组开始(我在您的示例中添加了三个数字以区分 3 x n n x 3 数组清除):

>>> import numpy as np

>>> rgbValues = np.array([14, 25, 19, 24, 25, 28, 58, 87, 43, 1, 2, 3])
>>> rgbValues.shape
(12,)

并将其 reshape 为 n x 3:

>>> lmsValues = rgbValues.reshape(-1, 3)
>>> lmsValues
array([[14, 25, 19],
       [24, 25, 28],
       [58, 87, 43],
       [ 1,  2,  3]])
>>> lmsValues.shape
(4, 3)

如果您希望每个元素的形状都是 3 x 1,也许您只想转置数组。这将切换行和列,因此形状为 3 x n

>>> lmsValues.T
array([[14, 24, 58,  1],
       [25, 25, 87,  2],
       [19, 28, 43,  3]])

>>> lmsValues.T.shape
(3, 4)

>>> lmsValues.T[0]
array([14, 24, 58,  1])

>>> lmsValues.T[0].shape
(4,)

如果您确实希望 lmsValues 中的每个元素 成为一个1 x 3 数组,您可以这样做,但它必须是形状为 n x 1 x 3 的 3d 数组:

>>> lmsValues = rgbValues.reshape(-1, 1, 3)
>>> lmsValues
array([[[14, 25, 19]],

       [[24, 25, 28]],

       [[58, 87, 43]],

       [[ 1,  2,  3]]])

>>> lmsValues.shape
(4, 1, 3)

>>> lmsValues[0]
array([[14, 25, 19]])

>>> lmsValues[0].shape
(1, 3)

关于python - 无法 reshape numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20253163/

相关文章:

python - 按组排序 float 列表

javascript - 多维javascript

python - 有没有办法将 Tkinter 与 Google Colaboratory 一起使用?

python - 如何遍历 .dat 文件并将每组行的特定列 append 到数组

python - 是否有相当于 MATLAB 的 conv2(h1,h2,A ,'same' ) 的 python ?

java - Java多维数组上的多种类型

c++ - 一种动态分配多维数组的方法

python - 无法使用 pudb 进行多处理

python - 无法使用 strptime 解析日期时间

python - 按索引之和对 NumPy 数组的元素进行分组