Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 2D float numpy array to 2D int numpy array?

Tags:

python

numpy

How to convert real numpy array to int numpy array? Tried using map directly to array but it did not work.

like image 998
Shan Avatar asked Jun 03 '12 20:06

Shan


People also ask

How do I convert a float to an int in NumPy?

To convert numpy float to int array in Python, use the np. astype() function. The np. astype() function takes an array of float values and converts it into an integer array.

How do you split a 2D array in NumPy Python?

For splitting the 2d array,you can use two specific functions which helps in splitting the NumPy arrays row wise and column wise which are split and hsplit respectively . 1. split function is used for Row wise splitting. 2.


2 Answers

Use the astype method.

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]]) >>> x array([[ 1. ,  2.3],        [ 1.3,  2.9]]) >>> x.astype(int) array([[1, 2],        [1, 2]]) 
like image 79
BrenBarn Avatar answered Sep 22 '22 04:09

BrenBarn


Some numpy functions for how to control the rounding: rint, floor,trunc, ceil. depending how u wish to round the floats, up, down, or to the nearest int.

>>> x = np.array([[1.0,2.3],[1.3,2.9]]) >>> x array([[ 1. ,  2.3],        [ 1.3,  2.9]]) >>> y = np.trunc(x) >>> y array([[ 1.,  2.],        [ 1.,  2.]]) >>> z = np.ceil(x) >>> z array([[ 1.,  3.],        [ 2.,  3.]]) >>> t = np.floor(x) >>> t array([[ 1.,  2.],        [ 1.,  2.]]) >>> a = np.rint(x) >>> a array([[ 1.,  2.],        [ 1.,  3.]]) 

To make one of this in to int, or one of the other types in numpy, astype (as answered by BrenBern):

a.astype(int) array([[1, 2],        [1, 3]])  >>> y.astype(int) array([[1, 2],        [1, 2]]) 
like image 27
fhtuft Avatar answered Sep 22 '22 04:09

fhtuft