numpy.array Boolean mix with int

Question:

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 convert whole array to type int, I guess maybe the int class is higher than bool which makes 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 confuses me when I consider both of the situations.

Could you please explain this a little bit?

Asked By: BENY

||

Answers:

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])

you should used the dtype to desired data-type for the array.

Please check the document

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

For you second question, please check the description at the dtype parameter,

“If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. “

you create the array with no dtype parameter, and the minimum for the value type for hold the sequence object is the bool, when you assign a int value it will be change to bool.

Answered By: youDaily
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.