numpy 如何防止np.where将0变成'0'?

4xy9mtcn  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(206)

我想创建一个np.where的数组,里面有字符串和0。所以通常它的dtype是'object'。最小的例子:

A = np.array([[1,2,1],[2,1,2],[1,1,2]])
x = np.where(A==1,0,'hello')

结果我得到

array([['0', 'hello', '0'],
       ['hello', '0', 'hello'],
       ['0', '0', 'hello']], dtype='<U11')

我希望那些“0”是0。由于np.where没有dtype的参数,我不知道如何做,除非在之后替换它们。必须有一个更好的方法来做。

kgsdhlau

kgsdhlau1#

您可以使用对象数组做为where的第一个输入值:

x = np.where(A==1, np.zeros_like(A).astype(object), 'hello')

输出量:

array([[0, 'hello', 0],
       ['hello', 0, 'hello'],
       [0, 0, 'hello']], dtype=object)

相关问题