Numpy copysign – Change the sign of x1 to that of x2, element-wise.

Featured Image

In this article, we understand and implement numpy.copysign() which is a NumPy function, as NumPy is an array processing package numpy.copysign() used to change signs of two given arrays.

What is numpy.copysign()?

The numpy.copysign() function in NumPy is used to convert the sign of an input array x1 to that of another x2 element-wise.


numpy.copysign(x1, x2, /, out=None, *, where=True)


x1:array_likeThis represents the input array whose sign is to be changed.Required
x2:array_likeThis represents the array whose sign is copied to x1.Required
outThis represents the location where the result is stored.Optional
whereThis is the condition over which the input is being broadcast. The resulting array will be set to the ufunc result at a given location where this condition is true.Optional
**kwargsThis represents other keyword arguments.Optional
Numpy -copysign syntax paramter

Return Value

The corresponding values of x1 with the sign of x2. This is a scalar if both x1 and x2 are scalars.

Examples of using numpy.copysign()

Importing NumPy library ,declaring and printing the arrays x1 and x2.

import numpy as np

x1 = np.array([1, 2, 3])
x2 = np.array([-1, -2, 3])
[1 2 3]
[-1 -2  3]

Here we have imported numpy library as np. We created the arrays x1 and x2 using the numpy array() function.

Example 1: Basic usage of numpy.copysign()

arr = np.copysign(x1, x2)

The output array arr will contain all the elements of array x1 with their signs equal to the signs of their corresponding element in array x2.

The output is calculated as:

  • x1[0] = 1 -> put sign of x2[0] => -1
  • x1[1] = 2 -> put sign of x2[1] => -2
  • x1[2] = 3 -> put sign of x2[2] => +3


[-1. -2.  3.]

Example 2: putting x2 as an integer instead of an array

import numpy as np
x1 = [100, -2, 34, 11 , 78 , -90]
print(np.copysign(x1, -7))

Here we have only a single integer as x2, therefore every element of array x1 will get the negative sign from -7 and the output contains all negative elements.


[-100.   -2.  -34.  -11.  -78.  -90.]

Example 3: Storing the result

import numpy as np
x1 = [100, -2, 34, 11 , 78 , -90]
arr = np.array(np.zeros(6))
np.copysign(x1, -7 , out=arr)

np.zeros(i) is used to return an array of i zeros. Here we have declared an np array with a dimension equal to that of x1. to store the result we get from np.copysign() using the out parameter. The output prints the array storing the result after copysign function is executed.


[-100.   -2.  -34.  -11.  -78.  -90.]


We have understood and implemented the numpy.copysign() function directly and also after storing the result in a different NumPy array using out parameter. numpy.copysign() is used to convert the sign of an input array x1 to that of another x2 element-wise.