[Numpy-discussion] Permuting sparse arrays

Robert Kern robert.kern at gmail.com
Wed Jan 25 10:23:51 EST 2012


On Wed, Jan 25, 2012 at 15:12, Edward C. Jones <edcjones at comcast.net> wrote:
> I have a vector of bits where there are many more zeros than one.  I
> store the array as a sorted list of the indexes where the bit is one.
> If the bit array is (0, 1, 0, 0, 0, 1, 1), it is stored as (1, 5, 6).
> If the bit array, b, has length n, and p is a random permutation of
> arange(n), then I can permute the bit array using fancy indexing: b[p].
> Is there some neat trick I can use to permute an array while leaving it
> in the list-of-indexes form?  Currently I am doing it with a Python loop
> but I am looking for a faster way.

Use argsort() to get the "inverse" of the permutation. Then
fancy-index the inverse with the list-of-indexes array.

[~/scratch]
|28> b
array([0, 1, 0, 0, 0, 1, 1])

[~/scratch]
|29> loi
array([1, 5, 6])

[~/scratch]
|30> p = np.random.permutation(len(b))

[~/scratch]
|31> ps = p.argsort()

[~/scratch]
|41> p
array([2, 3, 5, 4, 6, 1, 0])

[~/scratch]
|42> ps
array([6, 5, 0, 1, 3, 2, 4])

[~/scratch]
|43> ps[loi]
array([5, 2, 4])

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list