Convert an array of floats to integer

Asked

Viewed 7,922 times

9

Suppose the following:

import numpy as np

a = np.array ( [1.1, 2.2, 3.3] )

How to convert this array to int without having to iterate each element or using another array?

Why do:

b = int(a)

Gives an error because it is only possible to convert an array of length 1 to int. So I try:

for i in a:
    int(i)
    # ou
    # i = int(i)

does not solve, because a, after the loop remains with the elements in float.

You would then have to use one more array to do this and iterate over this array:

b = np.zeros( a.shape )
for i in xrange(0, len(a))
    b[i] = int(a[i])

Returns me an array of integer numbers, yes, but still of type float, note the point...

print b
[1., 2., 3.]

How to then convert to int?

7 answers

6

Try this:

a = array( [1.1, 2.2, 3.3] )
b = array(a, 'int')
File "<stdin>", line 1, in ? TypeError: Array can not be safely cast to required type

b = a.astype(Int)
  • I don’t understand your answer... can you elaborate better? It seems that what you suggest to try, unlike my other answer, also gives error and ends up doing the same...

  • Yes, but there is one more option, in case. astype() do not solve, what can occur, I do not know why, more with me has happened and after doing so I had no more problems with it...

  • can you explain your answer better? I’m having trouble understanding how the error you present is relevant...

  • If there was any mistake it is because the first way did not work, then yes in this case I use the . astype()...

  • Hum! Now yes! Understood.

  • corrected the Int, that there is no python me (2.7 at least), and I switched to 'int'. But I couldn’t reproduce the mistake you showed.

  • It does not have to necessarily occur, it is a prevention if it occurs, because it may occur, I did not find out why, but when it occurred I managed to solve the way I put....

Show 2 more comments

5

The arrays of the type numpy.ndarray has a method for type conversion:

import numpy as np

a = np.array( [1.1, 2.2, 3.3] )
b = a.astype('int')
print b
[1, 2, 3]

Care should be taken, however, when dealing with very large arrays, since the astype creates a copy of the array in memory.

  • 1

    if it is a one-dimensional array, you can do: b = map(int, a). But this will not work for multidimensional arrays.

4

I think an iteration by list already solves your problem without needing the astype.

Using list compression it is possible to perform this conversion in a much simpler way:

a = [1.1,2.2,3.3]
b = [int(x) for x in a]

The result of print b will be:

>>[1, 2, 3]

Of course, this will only be valid if they are valid elements to convert, if there are invalid elements (which cannot be converted to integer type), an exception will be returned. In case the ideal would be using a block try\except, if you are not sure of the list elements:

a = [1.1,2.2,3.3]
try:
  b = [int(x) for x in a]
except:
  print 'Nao foi possivel converter o numero.'
  • Very interesting! And I learned to use list compression because of your contribution. But it seems to me that this solution is more expensive than astype, right? It doesn’t imply iteration by the list, or anything like that?

  • 1

    Confirmed. Using timeit, astype converts a 200 position array into 0.010539054870605469 while the list compression does so in 0.2911491394042969, on my machine. The point is: astype is faster. And I have to type less...

  • Hence goes more of the possibilities, if you can use a lib, in the case a numpy, is rather a better solution, only that list understanding is already supported by the language itself. Anyway, at least the answer was good for something. (:

1

An alternative way, using map:

map(int, [1.2, 2.1, 3.1])

The map applies the function passed in the first parameter in each element of the list of the second parameter.

0

The method array class numpy supports in all 6 types of parameters. Among these parameters we have the dtype. This, in turn, serves to identify the type of data desired for the object array.

See here more details.

This way we can implement an algorithm that converts all elements to the type int. This algorithm is...

from numpy import array

a = array([1.1, 2.2, 3.3])
b = array(a, int)
print(b)

0

Numpy arrays have an associated type, and the default is float. To create an ints array, you will invariably have to create an array new. On the other hand, this is quite easy:

b = np.array( a, dtype=np.int32)

0

For some value to be valid to transform into int, it has to be a "practically int".

just separate the whole part of the decimal part:

int = float - (float % 1);

(I do not know how is mod in python, I believe it is %.)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.