Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

put numpy array items into "bins" [duplicate]

I have a numpy array with some integers, e.g.,

a = numpy.array([1, 6, 6, 4, 1, 1, 4])

I would now like to put all items into "bins" of equal values such that the bin with label 1 contains all indices of a that have the value 1. For the above example:

bins = {
    1: [0, 4, 5],
    6: [1, 2],
    4: [3, 6],
    }

A combination of unique and wheres does the trick,

uniques = numpy.unique(a)
bins = {u: numpy.where(a == u)[0] for u in uniques}

but this doesn't seem ideal since the number of unique entries may be large.

like image 778
Nico Schlömer Avatar asked Jul 19 '26 17:07

Nico Schlömer


1 Answers

Defaultdict with append would do the trick:

from collections import defaultdict

d = defaultdict(list)

for ix, val in enumerate(a):
  d[val].append(ix)
like image 116
Grisha Avatar answered Jul 21 '26 08:07

Grisha