Explain Codes LogoExplain Codes Logo

Convert 2D float array to 2D int array in NumPy

python
numpy
dataframe
precision-control
Anton ShumikhinbyAnton Shumikhin·Oct 13, 2024
TLDR

Conveniently, convert your 2D float array to an int array in NumPy with astype(int). Here's the ongaku (音楽 - music in Japanese):

import numpy as np float_array = np.array([[1.7, 2.5], [3.1, 4.8]]) int_array = float_array.astype(int) # Decimals point bye-bye

Output: [[1 2] [3 4]], decimals have left the ranks, no rounding, just truncation.

Controlling conversion and rounding

We can steer the conversion process by using methods like np.rint, np.floor, np.ceil, or np.trunc before the conversion. This allows us to decide on the rounding behavior - be the captain of the conversion ship.

# Rounding before conversion rounded_array = np.rint(float_array).astype(int) # Round then downcast like in a medieval drama

This approach provides precision control. You are the puppet master pulling the strings of your conversions, so that no digit falls out of line!

Speed and structure

Maintaining the dimensionality and shape of your array is just a matter of courtesy during this conversion party. astype method assures this while also keeping an eye on performance. If the guest at the party is a NumPy array already, astype(copy=False) avoids unnecessary replication.

int_array = float_array.astype(int, copy=False) # Work smarter, not harder

This setup ensures efficiency and performance. Perfect for large datasets where memory is as precious as gold in Fort Knox.

There's always another way

There's never one answer, astype being a common method, and np.asarray with dtype=int as the road less traveled for conversion.

int_array = np.asarray(float_array, dtype=int) # New kid on the block

This alternative shines when dealing with data that might not already be a NumPy array. It's a two-in-one deal: conversion and change of type.

Special cases: All's fair in love and conversions

Be mindful of precision loss when you swap from float to int as decimals bid their farewell. Not only that, but truncation tends to zero, which might not sit well with negative numbers.

# Special case handling negative_floats = np.array([[-1.7, -2.5], [-3.1, -4.8]]) int_array = np.floor(negative_floats).astype(int) # Negative values get special treatment

To tackle such bumpy roads, use explicit rounding behavior that's tailor-fit to your data.