0

I am trying to standardize a numpy array. I seem to be doing something wrong as the value of some elements of the output array is incorrect. I'd appreciate any help. Please find the code below: PYTHON CODE:

from numpy import loadtxt
import numpy as np
import math
class matrix(object):
 """A matrix class."""
 def __init__(self):
 self.array_2d = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
 def standardise(self):
 rows, columns = self.array_2d.shape
 temp = self.array_2d
 for j in range(columns):
 for i in range(rows):
 self.array_2d[i,j] = (temp[i, j] - min(temp[:, j])) / (max(temp[:, j]) - min(temp[:, j]))
m = matrix()
print(m.array_2d, "\n")
m.standardise()
print(m.array_2d)
asked Jul 30, 2022 at 13:42
2
  • can you add the desired output? Commented Jul 30, 2022 at 13:44
  • temp = self.array_2d doesn't make a copy of array_2d: it just makes the name temp point to the same array. So in your for loop, temp points to the same array that you've been changing in previous iterations of the loop, not to the original array. Commented Jul 30, 2022 at 14:56

1 Answer 1

1

If what you want to do is just to scale the matrix you dont have to do it in a for loop. You can do like this because Numpy is vectorized by default.

a = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
scaled_a = (a - a.min(axis=1))/(a.max(axis=1) - a.min(axis=1))
answered Jul 30, 2022 at 13:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.