Home > Software design >  Replacement of array elements with strings in Numpy
Replacement of array elements with strings in Numpy

Time:08-27

I want to replace the elements of an array (which contains numbers) with strings.For example I want "1" to be replaced with "a", I want "2" to be replaced with "b", and I want "3" to be replaced with "c". I did the following and didn't work for me. Can anyone suggest a way to resolve the issue?

test = np.where(test==1, "a", test)
test = np.where(test==2, "b", test)
test = np.where(test==3, "c", test)

CodePudding user response:

your looking for np.select it works by giving np.select a list of conditions, and a list of choices, and if the condition is true, it will replace that value with the same index from the choice list, if not, then it will use the default value, the 3rd positional argument in np.select

CODE:

import numpy as np
test = np.array([1,2,3,4,5,6,7,1,3,2,5]) 
condlist = [test==1 ,test==2, test==3]
choicelist = ['a', 'b', 'c']

test = np.select(condlist, choicelist, test)
test

OUTPUT:

array(['a', 'b', 'c', '4', '5', '6', '7', 'a', 'c', 'b', '5'],
  dtype='<U11')

CodePudding user response:

In your code, after the first modification, dtype of the array will be changed from int or float to <U11, so, test==2 and test==3for the next lines must be written as strings. If:

test = np.array([[1, 5, 6], [1, 3, 2]])
# dtype --> int32

So, after the first line:

test = np.where(test==1, "a", test)
# dtype --> <U11

So, 2 and 3 must be written as string:

test = np.where(test=='2', "b", test)
test = np.where(test=='3', "c", test)

It is the cause of the error. np.select is another way.

  • Related