'Filter imaginary numbers

In this task, you will be filtering out complex elements from an array.

Create a (4,) array with values 3, 4.5, 3 + 5j and 0 using "np.array()". Save it to a variable array

Create a boolean condition real to retain only a real number using .isreal(array). (Note: .isreal(array) returns a Boolean value which is True if the number inside the array is a real number and False otherwise)

Now apply this Boolean condition i.e. real on array using Boolean indexing (explained in the topic) by array[real] and store it in variable real_array.

Similarly, create a Boolean condition imag to retain only complex numbers which you can do it using .iscomplex(array). This time create an array imag_array which contains only complex numbers using the Boolean condition array[imag] Test Cases: imag_array[0] == (3+5j) real_array[0] == (3 +0j) and real_array[1]== (4.5+0j)

My Code:

# Code starts here
import numpy as np

# initialize array
array = np.array([3, 4.5, 3 + 5j, 0])

# boolean filter
real = array.isreal(array)
real_array = array[True, True, False, True]

# boolean filter
imag = array.iscomplex[array]
imag_array = array[False, False, True, False]

# Code ends here

What is the error ??



Solution 1:[1]

You are not calling the iscomplex function properly. You should change imag = array.iscomplex[array] to imag = array.iscomplex(array), also it was showing me error for array.isreal, I changed it to np.isreal(array) and it worked.

# Code starts here
import numpy as np

# initialize array
array = np.array([3, 4.5, 3 + 5j, 0])

# boolean filter
real = np.isreal(array)
real_array = array[real]

# boolean filter
imag = np.iscomplex(array)
imag_array = array[imag]
# Code ends here

Solution 2:[2]

def reject_complex(arr):
    res = []
    for ii, bb in enumerate(np.iscomplex(arr)):
        if not bb:
            res.append(arr[ii])
    return res

Solution 3:[3]

In case you came here looking for how to filter out imaginary numbers and get a list of the real values, this does that to array.

array[np.isreal(array)].real

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 paul-shuvo
Solution 2 Weilory
Solution 3 WASDi