Issue
I have an array like a=[1, 2, 3, 4, 5, 6, 7]
. I want to split this array into 3 chunks of any size.
When I split this into 3 chunks, I get 3 subarrays: [array([1, 2, 3]), array([4, 5]), array([6, 7])]
.
My goal is to get an array with the average of the elements in a subarray: [2, 4.5, 6.5]
, since (1+2+3)/3=2
(first element), (4+5)/2=4.5
(second element), and so on.
I tried the following code:
import numpy as np
a=[1, 2, 3, 4, 5, 6, 7]
a_split=np.array_split(a, 3)
a_split_avg=np.mean(a_split, axis=1)
I am getting the following error: tuple index out of range
.
Solution
You're getting the error because np.array_split
returns a python list of numpy array, not a multidimentional numpy array, so axis
wouldn't work with it. Replace the last line with this:
a_split_avg = [np.mean(arr) for arr in a_split]
Answered By - saga
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.