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)
1 Answer 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
lang-py
temp = self.array_2d
doesn't make a copy ofarray_2d
: it just makes the nametemp
point to the same array. So in yourfor
loop,temp
points to the same array that you've been changing in previous iterations of the loop, not to the original array.