Reputation: 13
I'm a bit new to python and I have to write a function for class. It receives a numpy array and searches through it for certain integers. I use doctests to test the return values from the function and I'm receiving the dtype in my results.
For example:
Expected:
array([1,2,3])
Got:
(array([1,2,3], dtype=int64),)
The function will be auto-marked, so I'm unsure how to have it return correctly.
I did some research and it was suggested to use numpy.astype to change the type to int32, however I receive an error when trying to do this as such.
myarray = myarray.astype('int32')
Is there any way to have it not show the dtype?
Upvotes: 1
Views: 14784
Reputation: 121
On my 32-bit Windows Python and linux 64-bit install, the dtype is printed when the numpy array uses an integer representation that is not the system default.
For example, on 32-bit windows:
import numpy as np
test = np.array([1, 2, 3, 4])
repr(test)
prints array(1, 2, 3, 4)
, while
test = np.array([1, 2, 3, 4], dtype=np.int64)
has a string representation array[1, 2, 3, 4], dtype=int64
It is the other way around on the 64-bit linux install. It seems that you are on a 32-bit version, so int64 is not the default integer type.
It sounds like the solution you tried (getting the array as type int32) should work - what error message did you get? Perhaps try myarray = myarray.astype(np.int32)
Upvotes: 4
Reputation: 32511
Your function is returning a tuple (array([1,2,3], dtype=int64),)
. So when you try to do myarray.astype('int32')
you are trying to call this method on a tuple. Maybe you are using np.where
or another function that returns a tuple.
You either want to fix your function to return the array only, or do change that line of code to myarray = myarray[0].astype('int32')
.
Also, you can't "remove" a dtype
from a NumPy array. Every ndarray has a dtype
. I am not sure why it is shown in your doctest though. NumPy test code often uses np.allclose
to test array equality, so you may want to check this out if you have similar issues.
Upvotes: 3