0

I'm trying to use the numpy module (which I imported as np) to find the means of the column vectors and then substract the means from the columns. However, when I try to get the means and append it to an empty array, it starts with 0 and has the wrong values. Any ideas what I could be doing wrong?

rating2 = np.array(student_data.values[:,1:])
print(rating2)
means = np.empty([1,25])
for index in range(0,24):
    b = np.mean(rating2[:,index], axis = 0)
    print("b is", b)
    np.append(means,b)
A = np.array(means)
print(A)

I checked each mean that's being calculated, and it doesnt start with 0. I checked my indexing, and it seems right.

My output:

[[3 2 3 3 3 3 3 3 4 3 4 4 3 4 3 2 2 3 4 2 2 3 3 4 4]
 [2 3 4 3 2 3 4 3 3 4 5 3 4 3 3 1 1 3 3 2 1 3 3 4 3]
 [2 5 4 2 3 2 4 4 1 4 3 1 4 2 2 3 3 2 2 4 3 2 1 3 2]
 [3 4 3 3 3 3 3 3 3 3 3 2 3 3 3 3 3 3 3 4 4 3 3 3 3]
 [4 1 1 5 4 4 2 2 4 1 1 4 1 4 4 4 4 4 4 2 4 4 5 2 4]
 [4 2 2 4 3 3 2 3 4 2 2 4 2 4 4 3 3 4 4 2 3 4 4 3 4]
 [2 5 5 1 2 2 4 4 2 5 5 2 5 2 2 2 2 2 2 4 2 2 1 4 2]
 [3 4 3 3 3 3 3 3 2 3 3 2 3 2 3 4 4 3 2 4 4 3 2 2 2]
 [4 1 2 4 3 4 2 2 4 2 3 5 3 4 4 3 3 4 4 2 2 4 4 4 4]
 [3 4 3 3 3 3 3 3 2 3 2 2 3 2 3 4 4 3 2 4 4 3 3 2 2]]
b is 3.0
b is 3.1
b is 3.0
b is 3.1
b is 2.9
b is 3.0
b is 3.0
b is 3.0
b is 2.9
b is 3.0
b is 3.1
b is 2.9
b is 3.1
b is 3.0
b is 3.1
b is 2.9
b is 2.9
b is 3.1
b is 3.0
b is 3.0
b is 2.9
b is 3.1
b is 2.9
b is 3.1
[[0.  3.  3.1 3.  3.1 2.9 3.  3.  3.  2.9 3.  3.1 2.9 3.1 3.  3.1 2.9 2.9
  3.1 3.  3.  2.9 3.1 2.9 3.1]]
2
  • In general, loops and appending should be avoided when using NumPy. Have you looked at the numpy docs? Commented Apr 15, 2020 at 19:11
  • np.append is not a list.append clone. Don't use it in the same way. Commented Apr 15, 2020 at 19:26

1 Answer 1

1

This should work

import numpy as np

# your numpy array
matrix = np.random.random((10, 10))

# this is the column wise mean
mean = np.mean(matrix, axis=0)

# this line is broadcasting the mean to the matrix
matrix_without_mean = matrix - mean
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.