NumPy ndarray.real Attribute



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

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

If the array contains only real numbers, accessing the real attribute simply returns the original array.

Usage of the real Attribute in NumPy

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

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

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

Example: Accessing Real Part of Complex Array

In this example, we create a 2D complex array and use the real attribute to extract the real 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.real)

Following is the output obtained −

[[1. 3.]
 [5. 7.]]

Example: Real Part of Complex Array with Negative Values

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

import numpy as np

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

This will produce the following result −

[[-1. -3.]
 [-5. -7.]]

Example: Real Part of Array with Only Real Numbers

In this example, we use the real attribute on a real-valued array. Since the array contains no imaginary components, the real attribute simply returns the original array −

import numpy as np

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

Following is the output obtained −

[1 2 3 4]

Example: Real Part of Empty Complex Array

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

import numpy as np

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

The output obtained is as shown below −

[]
numpy_array_attributes.htm
Advertisements