Reputation: 139
Let's say I have a 5x5 array 'A'. I want to take the mean of five elements in that array. It is possible that one of these values is Nan. I thought something like this would work:
np.nanmean(np.array([A[1,1], A[2, 2:3], A[3, 1:3]]))
But it doesn't. I get
ValueError: setting an array element with a sequence.
I also tried concatenating, flattening and using a list instead of np.array, but without luck.
I'm sorry if this question is a duplicate. It seems like an easy problem, but I can't manage to figure it out and I find it hard to pick good search terms to find a solution online.
Upvotes: 0
Views: 156
Reputation: 13100
You can concatenate all the elements into an array before doing the mean:
np.nanmean(np.concatenate([[A[1,1]], A[2, 2:3], A[3, 1:3]]))
Note that I have placed A[1,1]
inside an extra list. This is subtle, and the root of your troubles: Though e.g. A[2, 2:3]
contains only a single number, it is still an array because it is constructed from a slice. On the other hand, A[1,1]
is just a number, not living inside of an array object. Your error message is telling you that mixing this bare number with the other arrays leads to trouble.
Upvotes: 1