NumPy ndarray.real

The ndarray.real attribute in NumPy is used to extract or modify the real part of a complex-valued array. If the array contains only real numbers, this attribute will return the same values.

Syntax

</>
Copy
ndarray.real

Return Value

Returns an array containing the real part of the complex numbers in the original array. If the array consists of real numbers only, it remains unchanged.


Examples

1. Extracting the Real Part from a Complex Array

In this example, we create a NumPy array with complex numbers and extract only the real parts using ndarray.real.

</>
Copy
import numpy as np

# Creating an array of complex numbers
arr = np.array([1 + 2j, 3 - 4j, 5 + 6j])

# Extracting the real part
real_part = arr.real
print(real_part)  # Output: [1. 3. 5.]

Output:

[1. 3. 5.]

The real parts of the complex numbers are extracted, returning a real-valued array.

2. Modifying the Real Part of a Complex Array

The real attribute allows direct modification of the real part of a complex array.

</>
Copy
import numpy as np

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

# Modifying the real part
arr.real = [10, 20, 30]

# Printing the updated array
print(arr)  # Output: [10.+2.j 20.-4.j 30.+6.j]

Output:

[10.+2.j 20.-4.j 30.+6.j]

The real part of each element is successfully modified while keeping the imaginary part unchanged.

3. Extracting the Real Part from a Purely Real Array

If an array contains only real numbers, accessing the real attribute returns the same array.

</>
Copy
import numpy as np

# Creating a real-valued array
arr = np.array([10, 20, 30])

# Extracting the real part
real_part = arr.real
print(real_part)  # Output: [10 20 30]

Output:

[10 20 30]

Since the array contains only real values, the output remains unchanged.