2

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.]
4
  • 2
    As a side note: Is there a reason you need to use empty and then fill in the values one by one, instead of just doing a = np.array([1, 2, 3])? That would have avoided the problem you're seeing, as the default dtype for an array constructed from a sequence is determined by the values of the sequence, so you would have gotten int; when it doesn't know the values, it doesn't have any information, so it has to default to float. Commented Nov 25, 2013 at 19:46
  • @abarnert, thanks for the asking but the point is I need to calcualte the values and I need a for loop for that. The problem is it doesn't do it always. For example numpy.asarray() will keep the format! Commented Nov 25, 2013 at 20:08
  • 1
    That's exactly the point: asarray or array can keep the type, because it knows the type; empty can't keep the type, because it doesn't. (Also, you can easily turn your for loop 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 a list to pass to np.array instead.) Commented Nov 25, 2013 at 20:48
  • 1
    This pastebin shows what I mean. Commented Nov 25, 2013 at 20:54

2 Answers 2

12

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')
Sign up to request clarification or add additional context in comments.

4 Comments

But why does it cast it to float automatically?!?!
Every NumPy array has a dtype. The default is float.
That seems nut always to be true, or maybe I am confused because for example numpy.asarray() will keep the format of int if the values are integer.
@Naji: It's always true. I explained this in my comment. When it knows the type you want while constructing the array, it can use that type. When it doesn't know the type you want until later, it has to guess the type at construction time, and it always guesses float.
5

Use dtype=int:

>>> a = np.empty(3, dtype=np.int)
>>> a[0]=1
>>> a[1]=2
>>> a[2]=3
>>> a
array([1, 2, 3])

As the default value for dtype is float for numpy.empty, so your assigned values gets converted to float.

empty(...)
    empty(shape, dtype=float, order='C')

Comments

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.