I'm looking for list-comprehension method or similar in Numpy to eliminate use of a for-loop eg. index_values is a Python dictionary list of lists (each list containing a different number of index values) and s is a numpy vector:
for i in range(33):
s[index_values[i]] += 4.1
Is there a method available that allows eliminating the for-loop?
What about:
I don't fully understand what kind of object
index_values
is. But if it were anndarray
, or could be converted to anndarray
, you could just do this:Edit: But it seems that won't work in this case. On the basis of your edits and comments, here's a method I think might work for you. A random list of lists with varying lengths...
...isn't hard to convert into an array:
If you know the length of the array, specify the
count
for better performance:Since your edit indicates that you want histogram-like behavior, simple indexing won't do, as pointed out by Robert Kern. So use
numpy.histogram
:histogram
is really constructed for floating point histograms. This means that bins has to be a bit larger than expected because the last value is included in the last bin, and so 48 and 49 would be in the same bin if we used the more intuitiverange(0, 50)
. The result is a tuple with an array of n counts and an array of n + 1 bin borders:Now we can scale the counts up by a factor of 4.1 and perform vector addition:
I have no idea if this suits your purposes, but it seems like a good approach, and should probably happen at near c speed since it uses only
numpy
anditertools
.