Introduction to NumPy trim_zeros
The numpy.trim_zeros() function is used to trim the leading and/or trailing zeros from a 1-D array or sequence.
Syntax:
numpy.trim_zeros(arr, trim)
Parameters:
- arr: 1-D array or sequence
- trim: trim is an optional parameter with a default value to be ‘fb’ (front and back) we can either select ‘f’ (front) or ‘b’ for the back.
Return: [trimmed]1-D array or sequence (without leading and/or trailing zeros as per user’s choice)
Code Examples of NumPy trim_zeros
Example 01: With default value trim=’fb’
# welcome to softhunt.net
import numpy as np
softhunt = np.array((0, 0, 0, 0, 1, 3, 5, 7, 0, 9, 0, 11, 0, 0))
# without trim parameter
# returns an array without leading and trailing zeros
res = np.trim_zeros(softhunt)
print(res)
Output:
[ 1 3 5 7 0 9 0 11]
Note: These programs will not run in online IDEs. Please test them on your systems to see how they operate.
Example 02: When trim=’f’
# welcome to softhunt.net
import numpy as np
softhunt = np.array((0, 0, 0, 0, 1, 3, 5, 7, 0, 9, 0, 11, 0, 0))
# without trim parameter
# returns an array without any leading zeros
res = np.trim_zeros(softhunt, 'f')
print(res)
Output:
[ 1 3 5 7 0 9 0 11 0 0]
Example 03: When trim=’b’
# welcome to softhunt.net
import numpy as np
softhunt = np.array((0, 0, 0, 0, 1, 3, 5, 7, 0, 9, 0, 11, 0, 0))
# without trim parameter
# returns an array without any leading zeros
res = np.trim_zeros(softhunt, 'b')
print(res)
Output:
[ 0 0 0 0 1 3 5 7 0 9 0 11]
Note: These programs will not run in online IDEs. Please test them on your systems to see how they operate.
FAQs
What is a NumPy Ndarray?
NumPy is a Python library for scientific and numerical applications, and it is the tool of choice for linear algebra computations.
The ndarray, which is a shorthand term for N-dimensional array, is the most important data structure in NumPy. The data in a ndarray is simply referred to as an array when dealing with NumPy. It’s a memory array with data of the same type, such as integers or floating-point values, that’s fixed in size.
How many dimensions can a NumPy array have?
Numpy arrays can have several dimensions in general. Starting with a 1-dimensional array and using the NumPy reshape() function to rearrange elements of that array into a new shape is one technique to generate such an array.
Conclusion
That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn. And make sure you check out our NumPy tutorials.
Suggested Articles: