How to Apply a Function to NumPy Elements

Problem Formulation and Solution Overview

As a Pythonista, coding issues may occur where you need to apply a function against NumPy elements.

To make it more fun, we have the following running scenario:

We have a NumPy array containing five (5) negative numbers related to an inconsistent inventory count. Therefore, the Vice-President of Rivers Clothing has asked you to resolve this issue one way or another.

πŸ’¬ Question: How would we update the NumPy elements to adjust accordingly?

We could replace these negative numbers with zeroes (0) with one of the following options:

  • Method 1: Use NumPy where()
  • Method 2: Use Slicing
  • Method 3: Use NumPy place()
  • Method 4: Use a For loop

Preparation

Before any data manipulation can occur, one (1) new library will require installation.

  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install this library, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.


$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installation was successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required library.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import numpy as np 

Method 1: Use NumPy where()

This code replaces all negative Inventory values with zeroes (0) using NumPy’s where() function. This function accepts the following parameters:

– A condition (inventory<0).
– A value to replace elements matching said condition (0).
– The array to apply the said condition (inventory).

inventory = np.array([-5, -3, -11, -17, -8])
inventory = np.where((inventory < 0), 0, inventory)
print(inventory)

What a concise way to process this change! The results save back to inventory.

Output

[0 0 0 0 0]

Method 2: Use Slicing

Another way to replace all negative Inventory values with zeroes (0) is to use the famous (or infamous) slicing method.

inventory = np.array([-5, -3, -11, -17, -8])
inventory[:] = 0
print(inventory)

This code uses the [:] slicing notation to reference all elements of the inventory array. The results save back to inventory.

Output

[0 0 0 0 0]

⭐ Note: NumPy uses the broadcasting feature to dynamically fit the shape of the left side with the right side of the slice assignment operation.

Here’s a short video guide on broadcasting:


Method 3: Use NumPy place()

This code replaces all negative Inventory values with zeroes (0) using NumPy’s place() function. This function accepts the following parameters:

– The array to apply the condition (inventory).
– A condition (inventory<0).
– A list containing a value(s) to replace matching elements ([0]).

inventory = np.array([-5, -3, -11, -17, -8])
np.place(inventory, inventory<0, [0])
print(inventory)

This method is slightly different than using where(). The results update inventory in place.

Output

[0 0 0 0 0]

Method 4: Use a For Loop

For this method, let’s assume the Inventory values are somewhat correct. You determined that the Inventory counts should be positive, not negative. One way to perform this task is it use a for Loop.

for idx, item in enumerate(inventory):
      inventory[idx] = abs(inventory[idx])  
print(inventory)

The above code identifies each element’s position (idx) and its corresponding value (item). Then, each element converts from a negative Inventory value to a positive value using abs(). Finally, the results save back to inventory.

Output

[5 3 11 17 8]

Summary

As you can see, there are a few ways to accomplish the same task. It is up to you to decide which method best meets your coding requirements.

Good Luck & Happy Coding!