How do I write a function that returns mean, median and trimmed mean in python?

Question:

I am attempting to write a function that will give me an output of mean, median and trimmed mean depending on what is chosen. This is the problem:

Suppose x is a vector. Write a function f(x,type) where the output is mean of x if type=“mean” median of x if type=“median” 10% trimmed mean of x if type=“trimmed”. For the trimmed mean, you may use the following function: from scipy import stats stats.trim_mean(x, 0.1)

I wrote the following code but I am not getting 3 for mean or 3 for median.

import numpy as np
x_vec = np.array([1,2,3,4,5])
def f(x_vec,median):
    x= median(x_vec)
    return x

I am not sure if the function (f(x,median) or median) I am using is correct or why it is not giving the correct output. What am I missing?

Asked By: camaya3

||

Answers:

Your code defines a function without calling it, there will therefore be no output.

Furthermore it seems to me that you want to pass in a function as a function argument. This is fine in principle but the function mean_trim requires a second argument. This suggests that you could use functools.partial to set the second argument, but alas the second argument is positional and partial can only set keyword arguments. To be able to use partial you can define a new function which takes a keyword argument which is then used a second argument.

import numpy as np
from scipy import stats
from functools import partial

x_vec = np.array([1,2,3,4,5])

def f(x_vec,fie=np.median):
    x= fie(x_vec)
    return x

def trim_mean(x,proportiontocut=0):
    return  stats.trim_mean(x, proportiontocut)

f(x_vec), f(x_vec,fie=partial(trim_mean,proportiontocut=0.25)), 
Answered By: Ronald van Elburg
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.