I have my numpy object as:
[array([1, 1, 1]) array([2, 2, 2])
array([3, 3, 3]) array([4, 4, 4])
array([5, 5, 5]) array([6, 6, 6])]
My goal is to get a list/array of averages in all sub arrays, i.e. get the list [1 2 3 4 5 6].
I am getting with both np.mean and np.average: [3.5 3.5 3.5] which is the average of all first, all second, all third elements.
I tried added an argument axis=1
, but then I am getting the error:
avg = a.mean(axis)
File "---/numpy/core/_methods.py", line 138, in _mean
rcount = _count_reduce_items(arr, axis)
File "---/numpy/core/_methods.py", line 57, in _count_reduce_items
items *= arr.shape[ax]
IndexError: tuple index out of range
I tried casting my object to np.array but this made no difference.
As I commented, this is a minimal reproduce of my problem:
import numpy as np
A = np.zeros((2,2), dtype=object)
A[0][0] = np.append(A[0][0], np.array([1]))
A[0][1] = np.append(A[0][1], np.array([2]))
print(np.array(A[0,:]).mean()) # ok
print(np.array(A[0,:]).mean(axis=0)) # ok
np.array(A[0,:]).mean(axis=1) # bad
CodePudding user response:
I think you wanted to write a.mean(axis=axis)
. Complete solution:
Code
from numpy import array
a = array(
[
array([1, 1, 1]),
array([2, 2, 2]),
array([3, 3, 3]),
array([4, 4, 4]),
array([5, 5, 5]),
array([6, 6, 6]),
]
)
axis = 1
print(a.mean(axis=axis))
Output
[1. 2. 3. 4. 5. 6.]
CodePudding user response:
>>> obj = [np.array([1, 1, 1]), np.array([2, 2, 2]), np.array([3, 3, 3]), np.array([4, 4, 4]), np.array([5, 5, 5]), np.array([6, 6, 6])]
>>> np.array(obj).mean(axis=1).tolist()
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
To get it as integers
>>> np.array(obj).mean(axis=1, dtype=np.int32).tolist()
[1, 2, 3, 4, 5, 6]
In your case,
import numpy as np
A = np.zeros((2,2), dtype=object)
A[0] = np.array([1])
A[1] = np.array([2])
A.mean(axis=1).tolist()
output: [1.0, 2.0]