w3resource

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


37. Copy Sign from One Array to Another

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.


For more Practice: Solve these Related Problems:

  • Implement a function that uses np.copysign to assign the sign of one array to the magnitude of another.
  • Test the function on two arrays of equal length and verify that the result has the sign of the second array.
  • Create a solution that handles cases where one of the arrays contains zeros or negative values.
  • Compare the output of np.copysign with manual element-wise conditional assignments for validation.

Go to:


PREV : Check Signbit Element-wise
NEXT : Compute Numerical Negation

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.