Rajkamal Mishra
Rajkamal Mishra

Reputation: 171

How to create ndarray with int values with empty() function?

The issue is whenever I am typing the ndarray it gives the values in float. I want the output in int only.

I have tried y = int(y1) but it is showing TypeError: only size-1 arrays can be converted to Python scalars.

var = (4, 5, 6)
length = len(var)
print(length)
from numpy import empty

y1 = empty([len(var)])
y = int(y1)
print(y)

i = 0
for x in var:
    print(x)
    print("i = %i" % i)
    y[i] = int(x)
    print(y[i])
    i = i + 1
print(var)
print(y)

I want the output in int type only and not in float. I have also tried inside for loop to change dtype while assigning the value each time. Is there any better way to do so?

Upvotes: 0

Views: 207

Answers (2)

asikorski
asikorski

Reputation: 922

To create an empty numpy array with specific type use:

import numpy as np
shape = (1,2,3)
arr = np.empty(shape=shape, dtype=np.int32)

Upvotes: 1

ForceBru
ForceBru

Reputation: 44878

You can specify the dtype like this:

>>> import numpy as np
>>> np.empty((3,5), dtype=np.int)
array([[ 805306368, -244667706,  382337028,  979432584,  360625744],
       [ 357830816,  357820336,  979432584,  979432576,  360007872],
       [ 382203840,  382204224,  382476528,  379622304,  357830816]])

Upvotes: 1

Related Questions