Convert an array of floats to integer

7

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 to:

b = int(a)

It 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 resolve, because a , after the loop remains with elements in float.

I 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 an array with the integers, yes, but still of type float , note the point ...

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

How to convert to int?

    
asked by anonymous 06.01.2014 / 00:50

6 answers

4

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)
    
06.01.2014 / 11:40
3

Arrays of type numpy.ndarray have 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 must be taken, however, when dealing with very large arrays, since astype creates a copy of the array in memory.

    
06.01.2014 / 00:50
2

I think a list iteration already solves your problem without needing astype.

By using list compression you can 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 count if they are valid elements to convert, if there are invalid elements (which can not be converted to integer type), an exception is returned. In case the ideal would be using a block try\except , in case you are not sure of the elements of the list:

a = [1.1,2.2,3.3]
try:
  b = [int(x) for x in a]
except:
  print 'Nao foi possivel converter o numero.'
    
24.01.2014 / 12:16
0

An alternate form, using map :

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

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

    
29.01.2014 / 14:36
0

Numpy arrays have an associated type, and the default is float . To create an array of ints, you'll invariably have to create a new array . On the other hand, this is fairly easy:

b = np.array( a, dtype=np.int32)
    
29.01.2014 / 16:13
0

For some value to be valid for transforming int, it has to be a "practically int".

Just detach the entire part of the decimal part:

int = float - (float % 1);

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

    
29.01.2014 / 16:38