python - Fast replacement of values in a numpy array -


I have a very large numerical array (containing one million elements) such as the one below:

  [0 6 6 1 2 7 6 2 3 8 7 3 4 9 8 5 6 11 10 6 7 12 11 7 8 13 12 8 9 14 13 10 11 16 15 11 12 17 16 12 13 18 17 13 14 1 9 18 15 16 21 20 16 17 22 21 17 18 23 22 18 19 24 23] and a small dictionary map for the replacement of some of the elements mentioned above    {4: 0, 9: 5, 14: 10, 19:15, 20: 0, 21: 1, 22: 2, 23: 3, 24: 0}  < / Pre> 

I want to change some elements according to the map above. The oval array is really large, and only a small group of elements (only in the form of keys in the dictionary) will be replaced by the most appropriate values. What is the fastest way to do this?

I believe there is an even more effective method here, but for now, try

  copy of numpy import to newArray = copy (theArray) k, in v. d.iteritems (): newArray [theArray == k] = v  

Testing for microbainchmarks and correct:

/ code / # / / / bin / env python2.7 numpy import, random, arange random.seed (0) data = random To Randint (30, size = 10 ** 5) D = {4: 0, 9: 5, 14: 10, 19:15, 20: 0, 21: 1, 22: 2, 23: 3, 24: 0 } Dk = d.keys () dv = d.values ​​() def f1 (a, d): b = copy (a) for k, v in d.iteritems (): b [a == k] = V return b Def F2 (A, D): In the xchange (lane) I: A [I] = DATT (A [I], A [I] DFF F3 (A, DK, DV) returns: mp = arange (0, max (A) +1) mp [dk] = dv return mp [a] a = copy (data) res = f2 (a, d) (f1 (data, D) == res) .all () 3) all () 3) () () () () () () (3) Thon2.7 -m time for 'f', f3, data, d, dk , DV '' F1 (data, D) '100 loops, best 3: 6.15 miles per loop $ Python 2.7 -M Import F1, F3, data, D, DK, DV '' F3 (data, DK, DV) from Muay -S 'w' 100 loops, best 3: 19.6 msec per loop

Comments

Popular posts from this blog

Eclipse CDT variable colors in editor -

AJAX doesn't send POST query -

wpf - Custom Message Box Advice -