[SciPy-User] "inverting" an array
Eric Hermes
ehermes at chem.wisc.edu
Tue Feb 4 14:54:44 EST 2014
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 <mailto: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 <mailto:SciPy-User at scipy.org>
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
>
>
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
--
Eric Hermes
J.R. Schmidt Group
Chemistry Department
University of Wisconsin - Madison
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20140204/eba58b20/attachment.html>
More information about the SciPy-User
mailing list