【发布时间】: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