NumPy ndarray.imag Attribute



The NumPy ndarray.imag attribute is used to access the imaginary part of a complex number in a NumPy array. It returns the imaginary component of the array elements, which is especially useful when working with complex numbers.

When an array contains complex numbers, the imag attribute helps you separate the imaginary part from the real part, allowing for more specific operations.

If the array contains only real numbers, accessing the imag attribute will return an array of zeros.

Usage of the imag Attribute in NumPy

The imag attribute can be accessed directly from a NumPy array to get its imaginary part.

It is often used when you need to isolate the imaginary component of complex numbers in mathematical and scientific computing tasks.

Below are some examples that demonstrate how imag can be applied to various arrays in NumPy.

Example: Accessing Imaginary Part of Complex Array

In this example, we create a 2D complex array and use the imag attribute to extract the imaginary part of the array −

import numpy as np

# Creating a 2-dimensional complex array
arr = np.array([[1+2j, 3+4j], [5+6j, 7+8j]])
print(arr.imag)

Following is the output obtained −

[[2. 4.]
 [6. 8.]]

Example: Imaginary Part of a Complex Array with Negative Values

In this example, we create a complex array with negative imaginary parts and use the imag attribute to access the imaginary components −

import numpy as np

# Creating a complex array with negative imaginary parts
arr = np.array([[-1-2j, -3-4j], [-5-6j, -7-8j]])
print(arr.imag)

This will produce the following result −

[[-2. -4.]
 [-6. -8.]]

Example: Imaginary Part of an Array with Only Real Numbers

In this example, we use the imag attribute on a real-valued array. Since the array contains no imaginary components, the imag attribute returns an array of zeros −

import numpy as np

# Creating a real-valued array
arr = np.array([1, 2, 3, 4])
print(arr.imag)

Following is the output obtained −

[0 0 0 0]

Example: Imaginary Part of an Empty Complex Array

In this example, we check the result of accessing the imag attribute on an empty array with complex numbers −

import numpy as np

# Creating an empty complex array
arr = np.array([], dtype=complex)
print(arr.imag)

The output obtained is as shown below −

[]
numpy_array_attributes.htm
Advertisements