1

So I want to write a function that performs z-score transformation for each element in an array and the function should return an array of the result. When I perform the transformation to every element in the array using a for loop its not a problem.

   x1 = np.array([[4,3,12],[1,5,20],[1,2,3],[10,20,40],[7,2,44]])
   mean = np.average(x1)
   std = np.std(x1)

   for i in x1:
       arr1 = ((i-mean)/std)
       print(arr1)

   type(arr1)

However when I use a for loop for the column 1 of the array I get float values.

for x in x1[:,1]:
    arr2 = ((i-mean)/std)
    print(arr2)
    
type(arr2)

What can I do to make sure arr2 that is returned is a 1 dimensional array.enter image description here

4
  • Please avoid posting pictures on SO and rather post the code/data itself here. Thank you. Commented Sep 1, 2020 at 0:12
  • did you mean to calculate the mean and average of columns/rows separately? the question is not clear to me. Maybe you can elaborate on it. Thank you Commented Sep 1, 2020 at 0:22
  • Thanks for the response Ehsan I have posted the code as well. No I just want to retrieve the "transformed" column/rows not calculate the mean of columns and rows separately. Commented Sep 1, 2020 at 0:26
  • Does the posted answer solves the issue? if not, could you please provide us with your desired output? Commented Sep 1, 2020 at 0:37

2 Answers 2

1

You do not need a loop to calculate that:

(x-x.mean())/x.std()

Example:

x = np.arange(3*4).reshape(3,4)
#[[ 0  1  2  3]
# [ 4  5  6  7]
# [ 8  9 10 11]]

(x-x.mean())/x.std()
#[[-1.59325501 -1.30357228 -1.01388955 -0.72420682]
# [-0.43452409 -0.14484136  0.14484136  0.43452409]
# [ 0.72420682  1.01388955  1.30357228  1.59325501]]

Then you can select any columns/rows you would like:

selecting first column:

((x-x.mean())/x.std())[:,0]
#[-1.59325501 -0.43452409  0.72420682]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ehsan, I think your code gets me the output I want.
0

If you want to have the same structure you presented, this can help you

a = np.array([])
for i in x1[:,1]:
    val = ((i-mean)/std)
    a = np.append(a,val)
type(a)

2 Comments

We are working with numpy, so looping should be avoided here as much as possible. Another answer illustrates a way to do it.
This is why I said ‘the same structure’. You’re right

Your Answer

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.