Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing every other element in NumPy

I can't for the life of me figure this out.

I'm trying to remove every other element in the second axis of an array. I did this in MATLAB with arr(:,:,2:2:end) = [];, but when I tried to do the same in Python and compare the two outputs, I get a different matrix.

I've tried arr = np.delete(arr,np.arange(0,arr.shape[2],2),2) and arr = arr[:,:,1::2], but neither seem to come up with something I get with MATLAB.



Example:

MATLAB

    disp(['before: ',str(arr[21,32,11])])
    arr(:,:,2:2:end) = [];
    disp(['after: ',str(arr[21,32,11])])

output:

    before: 99089
    after: 65699


Python

    print 'before: ' + str(arr[20,31,10])
    arr = arr[:,:,1::2] # same output as np.delete(arr,np.arange(0,arr.shape[2],2),2) 
    print 'after: ' + str(arr[20,31,10])

output:

    before: 99089
    after: 62360

I hope I'm not overlooking something fundamental.

like image 685
David Avatar asked Jul 13 '15 14:07

David


1 Answers

You are trying to delete every other element starting from the second element onwards in the last axis. In other words, you are trying to keep every other element starting from the first element onwards in that axis.

Thus, working the other way around of selecting elements instead of deleting elements, the MATLAB code arr(:,:,2:2:end) = [] would be equivalent to (neglecting the performance numbers) :

arr = arr(:,:,1:2:end)

In Python/NumPy, this would be:

arr = arr[:,:,0::2]

Or simply:

arr = arr[:,:,::2]
like image 157
Divakar Avatar answered Sep 28 '22 23:09

Divakar