0

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?

1
  • 1
    dtype is determined when you create the array. Assignments don't change that. Given you current level of understanding, I think creating a np.zeros(3, dtype=int) is a better idea. Or np.array(var). The dtype issues are same, but it reduces confusion over the initial values of the array. Commented Jun 11, 2019 at 16:05

2 Answers 2

1

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

Comments

1

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)

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.