Cupitor
Cupitor

Reputation: 11657

How to store int values in numpy.empty array?

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

Upvotes: 2

Views: 8790

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251041

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')

Upvotes: 5

unutbu
unutbu

Reputation: 880259

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')

Upvotes: 12

Related Questions