[Numpy-discussion] use slicing as argument values?

Chao YUE chaoyuejoy@gmail....
Thu Jul 12 15:46:39 CDT 2012


Hi Ben,

it helps a lot. I am nearly finishing a function in a way I think pythonic.
Just one more question, I have:

In [24]: b=np.arange(1,11)

In [25]: b
Out[25]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

In [26]: b[slice(1)]
Out[26]: array([1])

In [27]: b[slice(4)]
Out[27]: array([1, 2, 3, 4])

In [28]: b[slice(None,4)]
Out[28]: array([1, 2, 3, 4])

so slice(4) is actually slice(None,4), how can I exactly want retrieve a[4]
using slice object?

thanks again!

Chao

2012/7/12 Benjamin Root <ben.root@ou.edu>

>
>
> On Thu, Jul 12, 2012 at 3:38 PM, Chao YUE <chaoyuejoy@gmail.com> wrote:
>
>> Dear all,
>>
>> I want to create a function and I would like one of the arguments of the
>> function to determine what slicing of numpy array I want to use.
>> a simple example:
>>
>> a=np.arange(100).reshape(10,10)
>>
>> suppose I want to have a imaging function to show image of part of this
>> data:
>>
>> def show_part_of_data(m,n):
>>     plt.imshow(a[m,n])
>>
>> like I can give m=3:5, n=2:7, when I call function
>> show_part_of_data(3:5,2:7), this means I try to do plt.imshow(a[3:5,2:7]).
>> the above example doesn't work in reality. but it illustrates something
>> similar that I desire, that is, I can specify what slicing of
>> number array I want by giving values to function arguments.
>>
>> thanks a lot,
>>
>> Chao
>>
>>
>
> What you want to do is create slice objects.
>
> a[3:5]
>
> is equivalent to
>
> sl = slice(3, 5)
> a[sl]
>
>
> and
>
> a[3:5, 5:14]
>
> is equivalent to
>
> sl = (slice(3, 5), slice(5, 14))
> a[sl]
>
> Furthermore, notation such as "::-1" is equivalent to slice(None, None, -1)
>
> I hope this helps!
> Ben Root
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>


-- 
***********************************************************************************
Chao YUE
Laboratoire des Sciences du Climat et de l'Environnement (LSCE-IPSL)
UMR 1572 CEA-CNRS-UVSQ
Batiment 712 - Pe 119
91191 GIF Sur YVETTE Cedex
Tel: (33) 01 69 08 29 02; Fax:01.69.08.77.16
************************************************************************************
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20120712/4655fe22/attachment.html 


More information about the NumPy-Discussion mailing list