【问题标题】:Numpy - Array to MatrixNumpy - 数组到矩阵
【发布时间】:2022-01-24 19:12:13
【问题描述】:

我正在编写一个 python 脚本,在其中输入一个 numpy 数组并将其作为矩阵返回;但是,随着一些值的变化。运行此代码,我收到一条错误消息;

IndexError: arrays used as indices must be of integer (or boolean) type

arrays used as indices must be of integer (or boolean) type

我在下面附上了我当前的功能

def w1(X):
    """
    Input:
    - X: A numpy array

    Returns:
    - A matrix Y such that Y[i, j] = X[i, j] * 10 + 100
    """

    Y = np.asmatrix(X)

    for i in Y:
        for j in i:
            Y[i,j] = Y[i,j] * 10 + 100
    return Y


【问题讨论】:

  • 为什么不只是(X * 10 + 100).tolist()
  • @Chrispresso 因为你必须使用 numpy 来返回一个矩阵
  • 那么就做np.asmatrix(X * 10 + 100)
  • np.matrix 有一条注释说不再推荐使用它。但是这种迭代对于numpy 数组来说仍然是个问题。或列表(列表)。 for i in ['a','b','c']: print(i) 打印字母,列表的元素,而不是它们的索引。

标签: python arrays numpy matrix


【解决方案1】:

尝试以下方法:

import numpy as np


    def w1(X):
        """
        Input:
        - X: A numpy array
    
        Returns:
        - A matrix Y such that Y[i, j] = X[i, j] * 10 + 100
        """
    
        # Y = np.asmatrix(X)  # you probably won't need this
    
        height, width = X.shape
    
        for i in range(height):
            for j in range(width):
                X[i, j] = X[i, j] * 10 + 100
        return X
    
    
    if __name__ == "__main__":
        h, w = 3, 4
        X = np.arange(1, h*w+1).reshape(h, w)
        print(X)
    
        print(w1(X.copy()))
    
        # much faster
        Y = X * 10 + 100
        print(Y)

【讨论】:

  • 我实际上尝试过 Y = np.asmatrix(X * 10 + 100) 并返回通过测试的 Y,但不确定它是如何工作的
  • @CosmoJohnson 你可以简化你的功能。请参阅我的编辑。您也可以使用Y = X*10 + 100,这要快得多。我相应地更新了我的答案。
  • @CosmoJohnson Numpy 允许您对操作进行矢量化以加快计算速度,因此您不必单独访问数组的每个元素。
【解决方案2】:

塞缪尔写的答案是完美的。我会详细说明你犯的错误。

您的代码中的错误在该行中

for i in Y:
    for j in i:

Y 是一个 numpy 矩阵。将其视为 numpy 数组的数组。因此,当您编写上述代码时,在每次迭代中,i 是一个完整行。当您编写for j in i 时,j 采用矩阵的该行中存在的实际值,而不是遍历特定行的列号。这就是您在方法中面临索引问题的原因。希望你明白了!

【讨论】:

    猜你喜欢
    • 2011-03-21
    • 2012-05-28
    • 2015-02-04
    • 1970-01-01
    • 2021-10-25
    • 2013-11-26
    • 1970-01-01
    • 2020-10-25
    相关资源
    最近更新 更多