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:
JavaScript
x
3
1
A = np.array([[1,2,1],[2,1,2],[1,1,2]])
2
x = np.where(A==1,0,'hello')
3
As a result I get
JavaScript
1
4
1
array([['0', 'hello', '0'],
2
['hello', '0', 'hello'],
3
['0', '0', 'hello']], dtype='<U11')
4
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.
Advertisement
Answer
You could use an object array as first input values for where
:
JavaScript
1
2
1
x = np.where(A==1, np.zeros_like(A).astype(object), 'hello')
2
Output:
JavaScript
1
4
1
array([[0, 'hello', 0],
2
['hello', 0, 'hello'],
3
[0, 0, 'hello']], dtype=object)
4