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.


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]
链接地址: http://www.djcxy.com/p/86674.html

上一篇: 在哪里得到所有的注册表策略标志?

下一篇: 删除NumPy中的所有其他元素