Numpy trunc: A step-by-step Guide with Examples

 

numpy trunc step by step examples

In this blog post, we'll dive into the numpy trunc() function, exploring its functionality step by step with real-world examples and addressing common pitfalls through error handling.

$ads={1}

Understanding the Numpy 'trunc()' Function:



1. Basics of 'trunc()':



The 'numpy.trunc()' function is designed to truncate the decimal part of each element in an array, leaving only the integer part behind. This can be particularly useful in scenarios where you need to work with whole numbers or integers exclusively.



import numpy as np

# Create an array with floating-point numbers
original_array = np.array([3.14, -7.89, 10.45, -2.71])

# Apply trunc() to truncate the decimals
truncated_array = np.trunc(original_array)

print("Original Array:", original_array)
print("Truncated Array:", truncated_array)


Output:




Original Array: [ 3.14 -7.89 10.45 -2.71]
Truncated Array: [ 3. -7. 10. -2.]




The 'trunc()' function seamlessly handles both 1D and 2D arrays. Let's explore examples for each case.



import numpy as np

# 1D Array
array_1d = np.array([1.23, -4.56, 7.89])
truncated_1d = np.trunc(array_1d)

# 2D Array
array_2d = np.array([[2.34, -5.67], [8.91, -0.12]])
truncated_2d = np.trunc(array_2d)

print("Truncated 1D Array:", truncated_1d)
print("Truncated 2D Array:\n", truncated_2d)


Output:




Truncated 1D Array: [ 1. -4.  7.]
Truncated 2D Array:
[[ 2. -5.]
 [ 8. -0.]]


Error Handling with trunc():



1. ValueError for Non-Numeric Arrays:



It's essential to ensure that the input array contains numerical values. The 'trunc()' function will raise a ValueError if non-numeric elements are encountered.



non_numeric_array = np.array(['apple', 'banana', 'cherry'])

try:
    truncated_non_numeric = np.trunc(non_numeric_array)
except ValueError as ve:
    print(f"Error: {ve}")


2. TypeError for Unsupported Data Types:



The 'trunc()' function is designed to work with numeric data types. If you attempt to use it with unsupported data types, a TypeError will be raised.



unsupported_type_array = np.array(['chandra', 'kumar', 'Arun'])

try:
    truncated_unsupported_type = np.trunc(unsupported_type_array)
except TypeError as te:
    print(f"Error: {te}")

$ads={2}

 Conclusion:



In this guide, we've explored the 'numpy.trunc()' function step by step, demonstrating its application on both 1D and 2D arrays. Additionally, we've addressed potential errors and provided examples of error handling to ensure smooth execution of your code. Incorporating the 'trunc()' function into your NumPy toolkit will empower you to efficiently handle arrays with precision, making it a valuable asset in your data science and numerical computing endeavors.


Previous Post Next Post