w3resource

NumPy: Create a vector with values ​​from 0 to 20 and change the sign of the numbers in the range from 9 to 15


Change Sign of Range 9-15

Write a NumPy program to create a vector with values ​​from 0 to 20 and change the sign of the numbers in the range from 9 to 15.

The problem involves writing a NumPy program to generate a vector ranging from 0 to 20, with specific values modified. Specifically, the task requires changing the sign of numbers within the range of 9 to 15 while leaving the rest of the values unchanged. This involves leveraging NumPy's array manipulation capabilities to efficiently achieve the desired outcome.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a NumPy array 'x' containing integers from 0 to 20 using np.arange()
x = np.arange(21)

# Printing a message indicating the original vector 'x'
print("Original vector:")
print(x)

# Printing a message indicating changing the sign of numbers in the range from 9 to 15
# Using boolean indexing, multiplying elements between 9 and 15 by -1 to change their sign
x[(x >= 9) & (x <= 15)] *= -1

# Printing the modified vector 'x'
print("After changing the sign of the numbers in the range from 9 to 15:")
print(x) 

Output:

Original vector:
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20]
After changing the sign of the numbers in the range from 9 to 15:
[  0   1   2   3   4   5   6   7   8  -9 -10 -11 -12 -13 -14 -15  16  17
  18  19  20]                         

Explanation:

The above code creates an array of integers from 0 to 20 and negates the elements with values between 9 and 15 (inclusive).

At first the np.arange() function creates a NumPy array 'x' containing integers from 0 to 20.

Secondly x[(x >= 9) & (x <= 15)] *= -1 uses boolean indexing to modify a specific subset of elements in the array 'x'. The condition (x >= 9) & (x <= 15) creates a boolean mask that is True for elements with values between 9 and 15 (inclusive), and False for all other elements. The mask is then applied to the array 'x', and the selected elements (those with True values in the mask) are multiplied by -1, effectively negating them.

Finally print(x) prints the modified array to the console.

Visual Presentation:

NumPy: Create a vector with values ​​from 0 to 20 and change the sign of the numbers in the range from 9 to 15.

Python-Numpy Code Editor: