NumPy ndarray.imag

The ndarray.imag attribute in NumPy returns the imaginary part of a complex-valued array. It extracts the imaginary component from each element while keeping the same shape.

Syntax

</>
Copy
ndarray.imag

Return Value

Returns a NumPy array containing the imaginary part of each element in the original array. The shape remains the same as the input array.


Examples

1. Extracting Imaginary Parts from a Complex Array

In this example, we create a NumPy array with complex numbers and extract their imaginary parts using imag.

</>
Copy
import numpy as np  

# Creating a complex-valued NumPy array
arr = np.array([1 + 2j, 3 - 4j, 5 + 6j])  

# Extracting the imaginary parts
imaginary_parts = arr.imag  

print(imaginary_parts)  # Output: [ 2. -4.  6.]

Output:

[ 2. -4.  6.]

Each element of the array retains only its imaginary component, forming a new real-valued array.

2. Extracting Imaginary Parts from a 2D Complex Array

Here, we work with a 2D complex array and extract its imaginary components.

</>
Copy
import numpy as np  

# Creating a 2D complex NumPy array
arr = np.array([[1 + 1j, 2 + 3j], 
                [4 - 2j, 5 + 6j]])  

# Extracting the imaginary parts
imaginary_parts = arr.imag  

print(imaginary_parts)  # Output: [[ 1.  3.] [-2.  6.]]

Output:

[[ 1.  3.]
 [-2.  6.]]

The result maintains the same shape as the original array but contains only the imaginary values.

3. Modifying the Imaginary Part of an Array

The imag attribute can be modified, changing the imaginary component of complex numbers.

</>
Copy
import numpy as np  

# Creating a NumPy array with complex numbers
arr = np.array([1 + 2j, 3 + 4j, 5 + 6j])  

# Modifying the imaginary parts
arr.imag = [10, 20, 30]  

print(arr)  # Output: [ 1.+10.j  3.+20.j  5.+30.j]

Output:

[ 1.+10.j  3.+20.j  5.+30.j]

By assigning new values to the imag attribute, we can directly modify the imaginary components of the original array.

4. Extracting Imaginary Parts from a Complex Function Output

We can use the imag attribute to extract the imaginary part from results of complex-valued functions.

</>
Copy
import numpy as np  

# Creating an array of real values
real_values = np.array([0, np.pi / 2, np.pi])  

# Computing complex exponential
complex_results = np.exp(1j * real_values)  

# Extracting the imaginary part
imaginary_parts = complex_results.imag  

print(imaginary_parts)  # Output: [ 0.  1.  0.]

Output:

[0.0000000e+00 1.0000000e+00 1.2246468e-16]

The exp(1j * x) function produces complex results, from which we extract the imaginary part.