3

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?

2
  • @JamesLiu yep , there are lot of way can achieve this changes, I just wondering why. Commented Aug 9, 2018 at 1:51
  • 1
    If you don't specify dtype when you built the array, numpy will choose automatically Commented Aug 9, 2018 at 1:55

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is good explanation, still wondering why assign the value will change bace to bool type
The numpy array can only have a same type, the second array built with dtype bool so numpy will try to convert new data to bool type
@Wen 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. "
@saul ok fair enough

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.