0

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])

1 Answer 1

1

Averaging in 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.

Defining a get_average function

If you think you still want a get_average function, then:

def get_average(a, cols):
    return np.average(a[:,cols], axis=0)
Sign up to request clarification or add additional context in comments.

Comments

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.