Home > Software design >  Using where function on numpy matrices with mixed char and number
Using where function on numpy matrices with mixed char and number

Time:01-23

a = np.array([a,b,1,2,1,1])

I want to convert certain numbers to characters. (1 -> k) result below

[a,b,k,2,k,k]

I wrote the code

a = np.where((a == 1), 'k', a)

but I can't use the where function with a mixture of char and numbers. How can I use where function?

CodePudding user response:

This works with an object dtype:

a = np.array(['a','b',1,2,1,1], dtype=object)

np.where((a == 1), 'k', a)

Output:

array(['a', 'b', 'k', 2, 'k', 'k'], dtype=object)

CodePudding user response:

Changing the a definition to make sense:

In [12]: a = np.array(['a','b',1,2,1,1])
In [13]: a
Out[13]: array(['a', 'b', '1', '2', '1', '1'], dtype='<U21')

This is an array of strings - no numbers; With that in mind it is easy to change the strings '1':

In [14]: a=='1'
Out[14]: array([False, False,  True, False,  True,  True])
In [15]: np.where(a=='1', 'k', a)
Out[15]: array(['a', 'b', 'k', '2', 'k', 'k'], dtype='<U21')

or changing the '2':

In [16]: a[a=='2'] = 'k'
In [17]: a
Out[17]: array(['a', 'b', '1', 'k', '1', '1'], dtype='<U21')

You could switch to object dtype array, to keep strings and numbers. But be careful. In many ways such an array is the same as a list.

  • Related