[SciPy-User] "inverting" an array
Guyer, Jonathan E. Dr.
jonathan.guyer at nist.gov
Tue Feb 4 16:14:54 EST 2014
> On 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
>
>
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
More information about the SciPy-User
mailing list