首页 > 解决方案 > numpy.array Boolean mix with int

问题描述

When I create the numpy.array which has bool type mixed with int

np.array([True,True,100])
Out[656]: array([  1,   1, 100])

np.array([True,True,100]).dtype
Out[657]: dtype('int32')

It will converted whole array to type int, I guess maybe the int class is higher than bool which is make sense.


And, If I already have a bool type array as below :

#When I assign the value by using the index 
b=np.array([True,True,False])
b[2]
Out[659]: False
b[2]=100
b
Out[661]: array([ True,  True,  True])

It will treat the 100 to be bool True, this is make sense too.


However it confused me when I consider both of the situations.

Could you please explain this it a little bit.


Thank you so much.

Wen

标签: pythonnumpy

解决方案


Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32

import numpy as np

np.array([True,True,100])
Out[3]: array([  1,   1, 100])

np.array([True,True,100], dtype=bool)
Out[4]: array([ True,  True,  True])

您应该dtype为数组使用所需的数据类型。

请检查文件

https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.array.html

对于你的第二个问题,请检查dtype参数的描述,

“如果没有给出,那么类型将被确定为保持序列中对象所需的最小类型。”

您创建不带dtype参数的数组,并且保存序列对象的值类型的最小值是bool,当您分配一个int值时,它将更改为bool


推荐阅读