w3resource

NumPy: Change the sign of a given array to that of a given array, element-wise


Write a NumPy program to change the sign of a given array to that of a given array, element-wise.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array with integer values from -1 to 2
x1 = np.array([-1, 0, 1, 2])

# Displaying the original array x1
print("Original array: ")
print(x1)

# Assigning a floating-point value to x2
x2 = -2.1

# Displaying the sign of x1 with respect to x2, element-wise using np.copysign()
print("\nSign of x1 to that of x2, element-wise:")
print(np.copysign(x1, x2)) 

Sample Output:

Original array: 
[-1  0  1  2]

Sign of x1 to that of x2, element-wise:
[-1. -0. -1. -2.]

Explanation:

x1 = np.array([-1, 0, 1, 2]): x1 is a 1-dimensional NumPy array of integers, with the values [-1, 0, 1, 2].

x2 = -2.1: x2 is a scalar value of type float.

np.copysign(x1, x2): This code returns an array with the same magnitude as x1, but with the sign of x2, which is negative. Therefore, the output will be array([-1. -0. -1. -2.]), which is an array with the same magnitude as x1, but with the sign changed to negative.

Python-Numpy Code Editor: