How to convert a boolean 3D array to an int array?

时间:2018-03-25 20:36:42

标签: python matrix multidimensional-array type-conversion boolean

I need to convert a 3D True/False into 1/0

For ex:

x = np.array([0,0,-1,1,0,1,-1,1,0]).reshape(3,3)[:, np.newaxis]

I tried the methods which are used to convert array

[x>0]*1

But it gives only the boolean values,

[array([[[False, False, False]],

        [[ True, False,  True]],

        [[False,  True, False]]])]

Is there a way to convert this while keeping the structure of the matrix?

3 个答案:

答案 0 :(得分:2)

IIUC this should work:

(x>0).astype(int)

array([[[0, 0, 0]],

       [[1, 0, 1]],

       [[0, 1, 0]]])

or, what you did, but without forcing it into a list with the square brackets:

(x>0)*1

array([[[0, 0, 0]],

       [[1, 0, 1]],

       [[0, 1, 0]]])

答案 1 :(得分:0)

I would used map() function. Let's say the array is test and z the condition.

map(lambda x: map(lambda y: map(lambda z: int(z), y), x), test)

答案 2 :(得分:0)

这是我从阅读文档中得到的结果。

str.format

astype函数是你可以在这种情况下使用的函数,你可以将int传递给它,以便将数组转换为整数数组。同样来自文档,如果你将来需要再次使用它,它可以用于任何数组(例如也适用于2x2,1x1等)。我没有使用jupyter笔记本,但是当我在Python脚本中打印x时,输出就是你想要的。