[SciPy-User] "inverting" an array
nicky van foreest
vanforeest at gmail.com
Tue Feb 4 15:21:28 EST 2014
HI,
Thanks. What an elegant solutions!
bye
Nicky
On 4 February 2014 20:54, Eric Hermes <ehermes at chem.wisc.edu> wrote:
>
> On 2/4/2014 1:52 PM, Warren Weckesser wrote:
>
>
> On Tue, Feb 4, 2014 at 2:33 PM, nicky van foreest <vanforeest at gmail.com>wrote:
>
>> Hi,
>>
>> I am wondering whether a shortcut exists in numpy/scipy for the
>> following problem. The values in an array represent the number of
>> customers that arrive in a certain time slot, e.g.,
>>
>> a = [0,4,7,3,1,5, 0,0,0,]
>>
>> means that in time slot 1 4 customers arrive, in time slot 2 seven
>> arrive, and so on. Now I want to "invert" this array to compute the arrival
>> time of the i-th customer. Thus, customer 2 arrives in time slot 1,
>> customer 6 in time slot 2, and so on. For this problem I wrote the
>> following function:
>>
>> a = [0,4,7,3,1,5, 0,0,0,]
>> A = np.cumsum(a)
>>
>> def invert(A):
>> Ainv = np.empty(A[-1])
>> aprev=0
>> for i, a in enumerate(A):
>> Ainv[aprev:a] = i
>> aprev = a
>> return Ainv
>>
>>
>> Ainv= invert(A)
>>
>> print a
>> print A
>> print Ainv
>>
>> The output is
>>
>> [0, 4, 7, 3, 1, 5, 0, 0, 0]
>> [ 0 4 11 14 15 20 20 20 20]
>> [ 1. 1. 1. 1. 2. 2. 2. 2. 2. 2. 2. 3. 3. 3. 4. 5. 5. 5.
>> 5. 5.]
>>
>> Does anybody know whether this code can be made faster, or whether a
>> numpy/scipy function exists that establishes this in one go?
>>
>> thanks
>>
>> Nicky
>>
>>
> You can use `np.repeat`:
>
> In [10]: a
> Out[10]: [0, 4, 7, 3, 1, 5, 0, 0, 0]
>
> In [11]: np.repeat(np.arange(len(a)), a)
> Out[11]: array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5,
> 5])
>
>
> Warren
>
> I came up with a version that only uses python intrinsics:
>
> def invert(a):
> ainv = []
> for i, n in enumerate(a):
> ainv += [i]*n
> return ainv
>
> Eric
>
>
>
>
>>
>>
>>
>> _______________________________________________
>> SciPy-User mailing list
>> SciPy-User at scipy.org
>> http://mail.scipy.org/mailman/listinfo/scipy-user
>>
>>
>
>
> _______________________________________________
> SciPy-User mailing listSciPy-User at scipy.orghttp://mail.scipy.org/mailman/listinfo/scipy-user
>
>
> --
> Eric Hermes
> J.R. Schmidt Group
> Chemistry Department
> University of Wisconsin - Madison
>
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20140204/4e90e967/attachment.html>
More information about the SciPy-User
mailing list