As the following code shows, empty array replaces my int values with float ones. How can I prevent this?
import numpy as np
a=np.empty(3)
a[0]=1
a[1]=2
a[2]=3
print a
Output:
[1., 2., 3.]
Specify the dtype when you call np.empty:
a = np.empty(3, dtype='int')
If you do not specify a dtype, the default is float. This is the call signature of np.empty:
empty(shape, dtype=float, order='C')
float.numpy.asarray() will keep the format of int if the values are integer.float.
emptyand then fill in the values one by one, instead of just doinga = np.array([1, 2, 3])? That would have avoided the problem you're seeing, as the defaultdtypefor an array constructed from a sequence is determined by the values of the sequence, so you would have gottenint; when it doesn't know the values, it doesn't have any information, so it has to default tofloat.forloop for that. The problem is it doesn't do it always. For examplenumpy.asarray()will keep the format!asarrayorarraycan keep the type, because it knows the type;emptycan't keep the type, because it doesn't. (Also, you can easily turn yourforloop into an iterator, e.g., by wrapping it in a generator function, and then pass the iterator to, e.g.,np.fromiter. Or, of course, build alistto pass tonp.arrayinstead.)