In this tutorial, we will look at how to trim zeros in python from a numpy array with the help of some examples.

## What is numpy `trim_zeros()`

?

The `trim_zeros()`

function in numpy is used to trim leading and/or trailing zeros from a one-dimensional numpy array or sequence. The following is the syntax.

import numpy as np arr = np.trim_zeros(flit, trim='fb')

Here, “flit” is the numpy 1-d array or sequence from which you want to trim zeros and “trim” determines which zeros to trim. It is “fb” by default to remove zeros from the front and the back.

It returns the 1-d array or sequence after trimming the zeros. The input data type is preserved. For example, if you pass a list instead of a numpy array, it will return the trimmed sequence as a list.

Let’s look at some examples of the usage of the numpy `trim_zeros()`

function.

## 1. Trim leading and trailing zeros from 1d array

Pass the array as an argument to the trim_zeros() function.

import numpy as np # 1d array with leading and trailing zeros a = np.array([0, 0, 0, 2, 4, 5, 0, 7, 3, 1, 0, 0]) # remove leading and trailing zeros b = np.trim_zeros(a) # display the trimmed array print(b)

Output:

[2 4 5 0 7 3 1]

Here, we created a numpy array with zeros at the front and the end and then passed this array to the numpy trim_zeros() function. You can see that the leading and trailing zeros have been removed in the returned array.

**Data Science Programs By Skill Level**

**Introductory** ⭐

- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science

**Intermediate ⭐⭐⭐**

- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization

**Advanced ⭐⭐⭐⭐⭐**

- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science

**🔎 Find Data Science Programs 👨💻 111,889 already enrolled**

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Let’s confirm the type of b.

type(b)

Output:

numpy.ndarray

It’s a numpy array, which is expected since we passed a numpy array.

## 2. Trim only leading zeros from a 1d array

To only remove the leading zeros from the array, pass `'f'`

to the `trim`

parameter. It indicates that you want to trim zeros from the front. For example, in the above array, let’s just remove only the leading zeros.

# 1d array with leading and trailing zeros a = np.array([0, 0, 0, 2, 4, 5, 0, 7, 3, 1, 0, 0]) # remove only the leading zeros b = np.trim_zeros(a, trim='f') # display the trimmed array print(b)

Output:

[2 4 5 0 7 3 1 0 0]

You can see that the returned array has all the leading zeros removed.

## 3. Trim only trailing zeros from a 1d array

Similarly, you can remove just the trailing zeros from an array by passing `'b'`

to the `trim`

parameter. It indicates that you want to trim from the back. Let’s see an example.

# 1d array with leading and trailing zeros a = np.array([0, 0, 0, 2, 4, 5, 0, 7, 3, 1, 0, 0]) # remove only the trailing zeros b = np.trim_zeros(a, trim='b') # display the trimmed array print(b)

Output:

[0 0 0 2 4 5 0 7 3 1]

The returned array has all the trailing zeros removed.

## 4. Trim zeros from a list

The numpy trim_zeros() function also allows you to trim zeros from other sequence types such as lists, tuples, etc. Also, it preserves the data type of the sequence. That is, for a list, it will return a list with the zeros trimmed.

# list with leading and trailing zeros a = [0, 0, 0, 2, 4, 5, 0, 7, 3, 1, 0, 0] # remove leading and trailing zeros b = np.trim_zeros(a) # display the trimmed list print(b) # diplay the type of b print(type(b))

Output:

[2, 4, 5, 0, 7, 3, 1] <class 'list'>

We get a list with all the leading and trailing zeros removed.

For more on the numpy trim_zeros() function, refer to its documentation.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5

**Subscribe to our newsletter for more informative guides and tutorials. ****We do not spam and you can opt out any time.**

Tutorials on numpy arrays –

- How to sort a Numpy Array?
- Create Pandas DataFrame from a Numpy Array
- Different ways to Create NumPy Arrays
- Convert Numpy array to a List – With Examples
- Append Values to a Numpy Array
- Find Index of Element in Numpy Array
- Read CSV file as NumPy Array
- Filter a Numpy Array – With Examples
- Python – Randomly select value from a list
- Numpy – Sum of Values in Array
- Numpy – Elementwise sum of two arrays
- Numpy – Elementwise multiplication of two arrays
- Using the numpy linspace() method
- Using numpy vstack() to vertically stack arrays
- Numpy logspace() – Usage and Examples
- Using the numpy arange() method
- Using numpy hstack() to horizontally stack arrays
- Trim zeros from a numpy array in Python
- Get unique values and counts in a numpy array
- Horizontally split numpy array with hsplit()