2

I have a problem where I need to remove alternate columns and rows of a 2D numpy array.

I've tried using numpy.delete to do so but the results didn't turn out what I want to be...

for x in range(rows):
    if x %2 ==0:
        array_np=np.delete(array_np,1,axis=1)
for y in range(columns):
    if y %2 ==0:
        array_np=np.delete(array_np,1,axis=0) 

for eg.

[[1,2,3,4],

 [5,6,7,8],

 [9,10,11,12],

 [13,14,15,16]]

expected output:

[[1,3],

 [9,11]]

The array is quite large in size than this, but the idea is the same.

3
  • Possible duplicate of remove a specific column in numpy Commented Feb 6, 2019 at 8:02
  • You should look at: stackoverflow.com/questions/16632568/… might be helpful Commented Feb 6, 2019 at 8:03
  • I did, but that's kinda static. I have a large array and need to delete every alternate row and column from it. Commented Feb 6, 2019 at 8:04

2 Answers 2

2
import numpy as np

arr_np = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]])

arr_all_odd=np.delete(arr_np, list(range(1, arr_np.shape[0], 2)), axis=1)
arr_odd_odd=np.delete(arr_all_odd, list(range(1, arr_np.shape[1], 2)), axis=0)

print(arr_odd_odd)

Output:

[[ 1  3]
 [ 9 11]]

You can make arr_odd_even, arr_even_odd, or arr_even_even in the same way.

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

Comments

1

You can try generating odd number list using list(range(1, array.shape[0], 2)), then you can construct list of all columns you need to delete.

a = np.array([[1,2,3,4],
...  [5,6,7,8],
...  [9,10,11,12],
...  [13,14,15,16]])
>>> np.delete(a, range(1, a.shape[0], 2), axis=0)
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])
>>> np.delete(a, range(1, a.shape[1], 2), axis=1)
array([[ 1,  3],
       [ 5,  7],
       [ 9, 11],
       [13, 15]])

If you combine both you should achieve what I understand you want.

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.