.trunc()
In NumPy, the .trunc()
function truncates the decimal part of each element in an array, returning the integer part as a float. It is used to discard the fractional part without rounding the number.
Syntax
numpy.trunc(x, /, out=None, *, where=True)
x
: The input array (or a single number) whose elements are to be truncated.out
(Optional): A location where the result will be stored. If not provided, a new array is created and returned.where
(Optional): A boolean array or condition that specifies which elements to compute for. The default isTrue
, meaning the function operates on all elements ofx
.
It returns a new array (or a scalar if the input is a single value) with the decimal part truncated from each element, leaving the integer part as a float.
Example 1
The example demonstrates how .trunc()
truncates the decimal values in a NumPy array:
import numpy as nparr = np.array([3.14, -2.718, 1.618, -4.0])truncated = np.trunc(arr)print(truncated)
The output will be as follows:
[ 3. -2. 1. -4.]
The above example also shows that .trunc()
does not round but it simply removes the fractional part.
Example 2
The example below demonstrates how to selectively apply truncation using the where
parameter, allowing truncation only for elements meeting a specified condition while leaving others unchanged:
import numpy as np# Array of numbersnumbers = np.array([3.14, -2.718, 1.618, -4.0])# Truncate only the positive numbersresult = np.where(numbers > 0, np.trunc(numbers), numbers)# Print the original and modified arraysprint("Original Numbers:", numbers)print("Conditionally Truncated Numbers:", result)
The output will be as follows:
Original Numbers: [ 3.14 -2.718 1.618 -4. ]Conditionally Truncated Numbers: [ 3. -2.718 1. -4. ]
Here, truncation is only applied to elements where the value is greater than 0
, leaving other elements unchanged.
Codebyte Example
Run the following codebyte example to understand how the .trunc()
works:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours