How to convert a matrix of floats into a matrix of integers with numpy in python ?

Published: September 21, 2021

Tags: Python; Numpy;

DMCA.com Protection Status

Examples of how to convert a matrix of floats into a matrix of integers with numpy in python:

Create a matrix of floats with numpy

Let's first create a matrix of random floats with numpy:

import numpy as np

data = np.random.rand(4,5) * 100.0

data

returns for example

array([[66.09124948, 68.46065421, 22.16897645, 77.84098663, 44.46296743],
       [16.41751266, 63.95374579, 86.87471262, 93.30928078, 59.99831054],
       [90.28468277, 72.28498272, 42.50043126, 41.53685781, 18.79383665],
       [96.91022221, 76.97924353, 80.93969912, 65.56091301,  6.87342516]])

Check the type of a matrix

data.dtype

gives here:

dtype('float64')

Convert a matrix of floats into a matrix of integers

To convert a matrix of floats into a matrix of integers, a solution is to use numpy.ndarray.astype

data = data.astype(int)

data

gives then

array([[66, 68, 22, 77, 44],
   [16, 63, 86, 93, 59],
   [90, 72, 42, 41, 18],
   [96, 76, 80, 65,  6]])

Note than:

data.dtype

gives

dtype('int64')

References