replace array values efficiently

Hi, I am new to numpy and getting my hands on slowly. How do you replace integers from strings in an integer array. (1D) For example: array = {1,1,1,2,3,3,4} replace 1 with "apple" replace 2 with "cheery" replace 3 with "mango" replace 4 with "banana" I know the general solution, but I am looking for an efficient way, supported by numpy/scipy to do this kind of conversion as fast as possible. Thanks Prashant Add more friends to your messenger and enjoy! Go to http://messenger.yahoo.com/invite/

On Fri, Jan 9, 2009 at 01:19, Prashant Saxena <animator333@yahoo.com> wrote:
Hi,
I am new to numpy and getting my hands on slowly.
How do you replace integers from strings in an integer array. (1D)
For example:
array = {1,1,1,2,3,3,4}
replace 1 with "apple" replace 2 with "cheery" replace 3 with "mango" replace 4 with "banana"
I know the general solution, but I am looking for an efficient way, supported by numpy/scipy to do this kind of conversion as fast as possible.
I'd actually use a dictionary for this: In [1]: replacements = {1: 'apple', 2: 'cherry', 3: 'mango', 4: 'banana'} In [2]: map(replacements.get, [1,1,1,2,3,3,4]) Out[2]: ['apple', 'apple', 'apple', 'cherry', 'mango', 'mango', 'banana'] But if you really want to use numpy for this: In [3]: from numpy import * In [4]: replacements_array = array([None, 'apple', 'cherry', 'mango', 'banana'], dtype=object) In [5]: replacements_array[[1,1,1,2,3,3,4]] Out[5]: array([apple, apple, apple, cherry, mango, mango, banana], dtype=object) -- 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
participants (2)
-
Prashant Saxena
-
Robert Kern