numpy.array布尔值转换为二进制? [英] numpy.array boolean to binary?

查看:574
本文介绍了numpy.array布尔值转换为二进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python27中重写matlab代码.有一条matlab行,如下所示:

I am trying to rewrite a matlab code in python27. There is a matlab line as follows:

vector_C = vector_A > vector_B;

如果我尝试使用numpy在python中编写此代码,则将是相同的,但结果将是布尔数组而不是二进制数组.我希望结果以二进制形式出现.有没有办法让它返回二进制,还是我应该每次手动转换?有没有一种快速的转换方法?我是python的新手.谢谢.

If I try to write this in python using numpy it will be the same, but the result will be an array of booleans instead of binaries. I want the result to be in binaries. Is there a way to make it return binary or should I convert manually each time? Is there a quick way of converting it? I am new to python. Thanks.

推荐答案

即使vector_C可能具有dtype=bool,您仍然可以执行以下操作:

Even though vector_C may have dtype=bool, you can still do operations such as the following:

In [1]: vector_A = scipy.randn(4)

In [2]: vector_B = scipy.zeros(4)

In [3]: vector_A
Out[3]: array([ 0.12515902, -0.53244222, -0.67717936, -0.74164708])

In [4]: vector_B
Out[4]: array([ 0.,  0.,  0.,  0.])

In [5]: vector_C = vector_A > vector_B

In [6]: vector_C
Out[6]: array([ True, False, False, False], dtype=bool)

In [7]: vector_C.sum()
Out[7]: 1

In [8]: vector_C.mean()
Out[8]: 0.25

In [9]: 3 - vector_C
Out[9]: array([2, 3, 3, 3])

因此,简而言之,您可能无需执行任何其他操作.

So, in short, you probably don't have to do anything extra.

但是如果必须进行转换,则可以使用astype:

But if you must do a conversion, you may use astype:

In [10]: vector_C.astype(int)
Out[10]: array([1, 0, 0, 0])

In [11]: vector_C.astype(float)
Out[11]: array([ 1.,  0.,  0.,  0.])

这篇关于numpy.array布尔值转换为二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆