Home > Software engineering >  Difference between dtype = np.int and int when creating array
Difference between dtype = np.int and int when creating array

Time:10-09

I am confused with the difference between integer types.

For example, here is a numpy.array with dtype of np.int.

>>> arr_ = np.array([1,2], dtype = np.int)

Through the below code, it represents true that int is the same as np.int:

>>> int is np.int
Out[1]: True

However, when I select the first value of the array which is created with dtype of np.int, the below code outputs false.

>>> type(arr_[0]) is int
Out[2]: False

Why does the code output false, not true?

It seems like that dtype = np.int dose not applied on the arr_.

Why np.int dose not applied as a dtype on the array?

I've looked into this, but couldn't get what I need.

CodePudding user response:

In Python the types int, np.int32 and np.int64 are 3 different types:

  • int is the native Python multiprecision integer type able to represent any integer value (the only limit being available memory). For example 2**128 is a valid int value
  • np.int32 in the int32_t C integer type that can represent values using up to 32 bits, that is values between -2147483648 and 2147483647
  • np.int64 is the int64_t C integer type that can represent values using up to 64 bits, that is values between -9223372036854775808 and 9223372036854775807

And np.int is a (deprecated alias) for the native Python int type, the reason why int is np.int is true. But numpy integer arrays even with dtype=int receive an actual type of np.int32 or np.int64 because they have to be processed by C code so they have to by coerced to a fixed size integer type. If you really need to store true int values, you will have to use dtype=object but operations will no longer be vectorizable.

  • Related