[Numpy-discussion] Fw: array indices and dictionary

Arnar Flatberg arnar.flatberg@gmail....
Sun Sep 21 14:28:45 CDT 2008


On Sun, Sep 21, 2008 at 7:51 PM, Dinesh B Vadhia
<dineshbvadhia@hotmail.com>wrote:

>  Ooops, I should have said that this is easy to do with 2 for loops ie.
>
> import numpy
> from collections import defaultdict
> A =
> [[1 6 1 2 3]
>  [4 5 4 7 0]
>  [2 0 8 0 2]
>  [0 0 0 3 7]
>  [0 7 0 3 5]
>  [8 0 3 0 6]
>  [8 0 0 2 2]
>  [3 1 0 4 0]
>  [5 0 8 0 0]
>  [2 1 0 5 6]]
>
> dict = defaultdict(list)
> I = A.shape[0]
> J = A.shape[1]
> for i in xrange(0, I, 1):
>     for j in xrange(0, J, 1):
>         if a[i,j] > 0:
>             dict[i].append(j)
>
> I want to find a faster/efficient way to do this without using the 2 for
> loops.  Thanks!
>
> Dinesh
>
>
>  *From:* Dinesh B Vadhia <dineshbvadhia@hotmail.com>
> *Sent:* Sunday, September 21, 2008 10:28 AM
> *To:* numpy-discussion@scipy.org
> *Subject:* array indices and dictionary
>
> Hi!  Say, I've got a numpy array/matrix of the form:
>
> A =
> [[1 6 1 2 3]
>  [4 5 4 7 0]
>  [2 0 8 0 2]
>  [0 0 0 3 7]
>  [0 7 0 3 5]
>  [8 0 3 0 6]
>  [8 0 0 2 2]
>  [3 1 0 4 0]
>  [5 0 8 0 0]
>  [2 1 0 5 6]]
>
> I want to create a dictionary of row indexes (as the keys) mapped to lists
> of the column indexes of non-zero numbers in that row ie.
>
> dictionary_non-zeros = {
> 0: [0 1 2 3 4]
> 1: [0 1 2 3]
> 2: [0 2 4]
> 3: [3 4]
> ...
> 9: [0 1 3 4]
> }
>
> How can I do this?
>
> This code ...
>
> d = {}
> for number, row in enumerate(A):
>     d[number] = [value for value in row if value !=0]
> ... picks up the non-zero values in each row eg.
>
> d = {0: [1, 6, 1, 2, 3], 1: [4, 5, 4, 7], 2: [2, 8, 2], 3: [3, 7], ... 9:
> [2, 1, 5, 6]}
>
> But, I want to pick up the column index of non-zero elements per row.
>
> Thanks!
>
> Dinesh
>
>
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>

Hi

Perhaps,
dict(enumerate([row.nonzero()[0] for row in A]))

An empty index will be the output if a row is all zeros. I dont know if that
would be an issue

Arnar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20080921/a5934cd7/attachment.html 


More information about the Numpy-discussion mailing list