1

I have a list of numpy arrays, and want to remove elements based on a specific position.

[array([ 1, 2, nan, 4, nan]), 
array([ 5, 6, 7, 8, 9]),
array([ 5, 6, 7, 8, 9])]

I need to get the positions of all the np.nan and remove the corresponding columns, giving me:

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

Short of looping everything, I have no idea where to start!

2 Answers 2

2

Given that your list of arrays is named A:

A = [np.delete(row,np.argwhere(np.isnan(A[0]))) for row in A]

output:

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

Depending on your application however it might be better to use sams-studio's approach of creating one large numpy array. I would prefer that approach for most applications.

Sign up to request clarification or add additional context in comments.

Comments

2

I guess the easiest would be

# arr is your original list
arr = [np.array([ 1, 2, np.nan, 4, np.nan]),
       np.array([ 5, 6, 7, 8, 9]),
       np.array([ 5, 6, 7, 8, 9])]
return_array = np.asarray(arr)[:, ~np.isnan(np.asarray(arr)).any(axis=0)]
print(return_array)

This will return:

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

If you want to have a list of array, then you have to do additionally:

return_array = [r for r in return_array]

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.