'Numpy - Array to Matrix
I am writing a python script where I input a numpy array and return it as a matrix; however, with some of the values changed. Running this code, I get an error saying;
IndexError: arrays used as indices must be of integer (or boolean) type
arrays used as indices must be of integer (or boolean) type
I have attached my current function below
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
Solution 1:[1]
Try the following:
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)
Solution 2:[2]
The answer written by Samuel is perfect. I'll elaborate on the mistake you made.
The error in your code is in the line
for i in Y:
for j in i:
Y is a numpy matrix. Consider it as an array of numpy arrays. So when you write the above code, in each iteration, i is a complete row. When you write for j in i, j takes the actual values present in that row of the matrix instead of iterating through the column number of the particular row. That is why you are facing index issues in your method. Hope you got this!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Kunind Sahu |
