9.1 C
London
Friday, December 20, 2024
HomePandas in PythonDataFrame Functions in PythonHow to Map a Function Over a NumPy Array (With Examples)

How to Map a Function Over a NumPy Array (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to map a function over a NumPy array:

#define function
my_function = lambda x: x*5

#map function to every element in NumPy array
my_function(my_array)

The following examples show how to use this syntax in practice.

Example 1: Map Function Over 1-Dimensional NumPy Array

The following code shows how to map a function to a NumPy array that multiplies each value by 2 and then adds 5:

import numpy as np

#create NumPy array
data = np.array([1, 3, 4, 4, 7, 8, 13, 15])

#define function
my_function = lambda x: x*2+5

#apply function to NumPy array
my_function(data)

array([ 7, 11, 13, 13, 19, 21, 31, 35])

Here is how each value in the new array was calculated:

  • First value: 1*2+5 = 7
  • Second value: 3*2+5 = 11
  • Third value: 4*2+5 = 13

And so on.

Example 2: Map Function Over Multi-Dimensional NumPy Array

The following code shows how to map a function to a multi-dimensional NumPy array that multiplies each value by 2 and then adds 5:

import numpy as np

#create NumPy array
data = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

#view NumPy array
print(data)

[[1 2 3 4]
 [5 6 7 8]]

#define function
my_function = lambda x: x*2+5

#apply function to NumPy array
my_function(data)

array([[ 7,  9, 11, 13],
       [15, 17, 19, 21]])

Notice that this syntax worked with a multi-dimensional array just as well as it worked with a one-dimensional array.

Additional Resources

The following tutorials explain how to perform other common operations in NumPy:

How to Add a Column to a NumPy Array
How to Convert NumPy Array to List in Python
How to Export a NumPy Array to a CSV File

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories