# Use an index array to construct a new array from a set of choices with clip mode in Numpy

NumpyServer Side ProgrammingProgramming

#### Python Data Science basics with Numpy, Pandas and Matplotlib

Most Popular

63 Lectures 6 hours

#### Data Analysis using NumPy and Pandas

19 Lectures 8 hours

#### Numpy with Python

Most Popular

12 Lectures 3 hours

A new array from the set of choices is constructed using the np.ma.choose() method. The mode parameter is set to 'clip'. If mode='clip', values greater than n-1 are mapped to n-1; and then the new array is constructed.

Given an array of integers and a list of n choice arrays, this method will create a new array that merges each of the choice arrays. Where a value in index is i, the new array will have the value that choices[i] contains in the same place.

The choices parameter is the choice arrays. The index array and all of the choices should be broadcastable to the same shape.

The mode parameter specifies how out-of-bounds indices will behave −

• 'raise' : raise an error
• 'wrap' : wrap around
• 'clip' : clip to the range

## Steps

At first, import the required library −

import numpy as np

Set choices array −

arr_choices = np.array([[5, 10, 15, 20, 25], [50, 55, 60, 65, 70],
[100, 105, 110, 115, 120], [150, 155, 160, 165, 170], [200, 205, 210, 215, 220]])

Create a new array −

arr = np.array([2, 3, 4, 1, 8])

Displaying the array −

print("Array...\n",arr)

Displaying the choices array −

print("\nChoices Array...\n",arr_choices)

A new array from the set of choices is constructed using the choose() method. The mode parameter is set to 'clip'. Here, if mode='clip', values greater than n-1 are mapped to n-1; and then the new array is constructed:

arrRes = np.ma.choose(arr, arr_choices, mode='clip')
print("\nNew Array from set of choices...\n",arrRes)

## Example

import numpy as np

# set choices array
arr_choices = np.array([[5, 10, 15, 20, 25], [50, 55, 60, 65, 70], [100, 105, 110, 115, 120], [150, 155, 160, 165, 170], [200, 205, 210, 215, 220]])

# Create a new array
arr = np.array([2, 3, 4, 1, 8])

# Displaying the array
print("Array...\n",arr)

# Displaying the choices array
print("\nChoices Array...\n",arr_choices)

# A new array from the set of choices is constructed using the choose() method

# The mode parameter is set to 'clip'
# if mode='clip', values greater than n-1 are mapped to n-1; and then the new array is constructed
arrRes = np.ma.choose(arr, arr_choices, mode='clip')
print("\nNew Array from set of choices...\n",arrRes)

## Output

Array...
[2 3 4 1 8]

Choices Array...
[[ 5 10 15 20 25]
[ 50 55 60 65 70]
[100 105 110 115 120]
[150 155 160 165 170]
[200 205 210 215 220]]

New Array from set of choices...
[100 155 210 65 220]