Simran Kaur
Simran Kaur

Reputation: 277

Mean, variance and standard deviation in python

n,m = map(int,input().split())
A = []
for _ in range(n):
    A.append(map(int,input().split()))
A = numpy.array(A)

print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))

Can anyone tell me what I am doing wrong? I am getting error : numpy.AxisError: axis 1 is out of bounds for array of dimension 1

Also, I want the user to input the array of n x m dimensions. How can I add the m dimension check ?

Please help.

Upvotes: 0

Views: 483

Answers (1)

Karthik Dasari
Karthik Dasari

Reputation: 36

When you are trying to append elements in the array, you are taking the elements using the map function, a map function will always return a map object and you are just appending map objects as elements to the array. So, when you are trying to access axis=1 actually there is no axis=1 present in the array because the array contains a single row with map objects.

Here is the correct code without using list comprehension,

n,m = map(int,input().split())
A = []
for _ in range(n):
    A.append(list(map(int,input().split())))
A = numpy.array(A)
print(A)
print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))

Here is the code using list comprehension,

n,m = map(int,input().split())
A = []
for _ in range(n):
    A.append([int(x) for x in input().split()])
A = numpy.array(A)
print(A)
print (numpy.mean(A,axis = 1))
print (numpy.var(A,axis = 0))
print (round(numpy.std(A),11))

Upvotes: 2

Related Questions