[Numpy-discussion] Slice nested arrays, How to

William Ray Wing wrw at mac.com
Mon Jul 24 13:15:15 EDT 2017


> On Jul 24, 2017, at 10:37 AM, Bob <bobmerhebi at gmail.com> wrote:
> 
> Hello,
> 
> I created the following array by converting it from a nested list:
> 
>    a = np.array([np.array([ 17.56578416,  16.82712825,  16.57992292, 
> 15.83534836]),
>       np.array([ 17.9002445 ,  17.35024876,  16.69733472,  15.78809856]),
>       np.array([ 17.90086839,  17.64315136,  17.40653009,  17.26346787,
>        16.99901931,  16.87787178,  16.68278558,  16.56006419, 
> 16.43672445]),
>       np.array([ 17.91147242,  17.2770623 ,  17.0320501 , 
> 16.73729491,  16.4910479 ])], dtype=object)
> 
> I wish to slice the first element of each sub-array so I can perform
> basic statistics (mean, sd, etc...0).
> 

Have you considered using Pandas?  Assuming I understand what you are trying to do, that nested list could read directly into a Pandas 2D data frame. Extracting the first element of each column (or row) is then fast and efficient.

Bill
> How can I do that for large data without resorting to loops? Here's the
> result I want with a loop:
> 
>    s = np.zeros(4)
>    for i in np.arange(4):
>        s[i] = a[i][0]
> 
>    array([ 17.56578416,  17.9002445 ,  17.90086839,  17.91147242])
> 
> Thank you
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at python.org
> https://mail.python.org/mailman/listinfo/numpy-discussion



More information about the NumPy-Discussion mailing list