Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

Time for action – clipping and compressing arrays


Here are a few examples of ndarray methods. Perform the following steps to clip and compress arrays:

  1. The clip() method returns a clipped array, so that all values above a maximum value are set to the maximum and values below a minimum are set to the minimum value. Clip an array with values 0 to 4 to 1 and 2:

    a = np.arange(5)
    print("a =", a)
    print("Clipped", a.clip(1, 2))

    This gives the following output:

    a = [0 1 2 3 4]
    Clipped [1 1 2 2 2]
    
  2. The ndarray compress() method returns an array based on a condition. For instance, look at the following code:

    a = np.arange(4)
    print(a)
    print("Compressed", a.compress(a > 2))

    This returns the following output:

    [0 1 2 3]
    Compressed [3]
    

What just happened?

We created an array with values 0 to 3 and selected the last element with the compress() function based on the a > 2 condition.