Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.]
like image 403
Cupitor Avatar asked Feb 21 '26 09:02

Cupitor


2 Answers

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')
like image 144
unutbu Avatar answered Feb 22 '26 22:02

unutbu


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')
like image 33
Ashwini Chaudhary Avatar answered Feb 22 '26 22:02

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!