Reputation: 49
I've been going crazy trying to find a way out.
Input a 2D array and several column numbers, return the average of every number in those specific columns in the form of array.
I know how to output the average of all columns, but I have no idea how to output only specific columns' averages.
a = array([[0, 0,1], [1, 1,2], [3, 3,3]])
get_average(a,[0,1])
array([1.333333333, 1.333333333333])
Upvotes: 0
Views: 72
Reputation: 113814
numpy
numpy
has an average
function:
>>> import numpy as np
>>> a = np.array([[0, 0,1], [1, 1,2], [3, 3,3]])
>>> np.average(a[:,(0,1)], axis=0)
array([ 1.33, 1.33])
For np.average
, axis
specifies the array axis along with to average. axis=0
, for example, averages over the rows.
np.average
also offers weighted averages if you ever need them.
get_average
functionIf you think you still want a get_average
function, then:
def get_average(a, cols):
return np.average(a[:,cols], axis=0)
Upvotes: 1