1

I have a numpy array

A = np.array([[1, 2, 3, 4], 
             [2, float('inf'), 3, 4],
             [5, 6, 7, 8]])  

I would like to remove the lines that contain an infinite value in them so that the results would be

np.array([[1,2,3,4],
          [5,6,7,8]])

I tried to do A = A[float('inf') not in A], but the result is array([], shape=(0, 3, 4), dtype=float64).

I could do

B = []
for line in A:
    if float('inf') not in line:
        B.append(line)
A = np.array(B)

but is there a better way to do this?

2 Answers 2

3

Given that you have a NumPy array, a NumPy based solution will perform much better than using python lists.You can use np.isinf with any here:

A[~np.isinf(A).any(1)]

array([[1., 2., 3., 4.],
       [5., 6., 7., 8.]])

is_inf = np.isinf(A) # returns True when there is an Inf
print(is_inf)

array([[False, False, False, False],
       [False,  True, False, False],
       [False, False, False, False]])

is_inf_any = is_inf.any(1) # Checks is there are any Trues along axis 1 
                           # (hence reduces along that axis)
print(is_inf_any)

# array([False,  True, False])

~is_inf_any # applies a bitwise logical not
# array([ True, False,  True])
Sign up to request clarification or add additional context in comments.

5 Comments

Nice answer. What does it mean any(1) ?
What does the ~ mean?
~ means not. That means not isinf
.any(1) means it is checking if any line evaluates to True.
And the 1 in .any(1) is the axis along which to perform the comparison, I think
1

You could use a list comprehension for this.

A = np.array([line for line in A if float('inf') not in line])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.