I want to create an array with np.where that has strings and 0s in it. So usually its dtype would be 'object'. Minimal example:
A = np.array([[1,2,1],[2,1,2],[1,1,2]])
x = np.where(A==1,0,'hello')
As a result I get
array([['0', 'hello', '0'],
['hello', '0', 'hello'],
['0', '0', 'hello']], dtype='<U11')
I would like those '0's to be 0s. Since np.where has no argument for dtype, I don't know how to do this except by replacing them afterwards. There has to be a better way to do this.
CodePudding user response:
You could use an object array as first input values for where
:
x = np.where(A==1, np.zeros_like(A).astype(object), 'hello')
Output:
array([[0, 'hello', 0],
['hello', 0, 'hello'],
[0, 0, 'hello']], dtype=object)