What's the best way to get a list/array of element-wise means between an array and a constant?
Question:
Suppose I have my_array = np.array([2, 4, 6])
and I want to get another array that represents the mean of each element in my_array
and a constant, say, 2. So I want to return returned_array = [2, 3, 4]
. What is the best way to do this?
When I try np.mean(my_array, 2)
I get TypeError: only size-1 arrays can be converted to Python scalars
.
I can create my own mean function for this purpose:
def mean(a,b):
return (a+b)/2
and this works fine. This is obviously not an ideal way to do this. What is the best way? Why must everything in numpy be an ordeal?
Answers:
How about this:
import numpy as np
my_array = np.array([2, 4, 6])
other = 2
(my_array + other) / 2
# [2. 3. 4.]
It’s just the element-wise average of two numbers, which is the same as just dividing by two.
Suppose I have my_array = np.array([2, 4, 6])
and I want to get another array that represents the mean of each element in my_array
and a constant, say, 2. So I want to return returned_array = [2, 3, 4]
. What is the best way to do this?
When I try np.mean(my_array, 2)
I get TypeError: only size-1 arrays can be converted to Python scalars
.
I can create my own mean function for this purpose:
def mean(a,b):
return (a+b)/2
and this works fine. This is obviously not an ideal way to do this. What is the best way? Why must everything in numpy be an ordeal?
How about this:
import numpy as np
my_array = np.array([2, 4, 6])
other = 2
(my_array + other) / 2
# [2. 3. 4.]
It’s just the element-wise average of two numbers, which is the same as just dividing by two.