How to remove a subset of a 2d array?

I have an 800x800 array and I want to parse only the elements in its part. I need a new array without slice elements [5: -5.5: -5]. It is not necessary to return a 2d array, a flat array, or a list. Example:

import numpy >>> a = numpy.arange(1,10) array([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> a.shape = (3,3) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 

I need to drop the basic elements, for example:

 del a[1:2,1:2] 

I expect:

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

I tried using numpy.delete (), but it seems to work on one axis at a time. I wonder if there is a more direct way to do this.

+6
source share
2 answers

You can use a logical array to index your array in any way convenient for you. This way, you do not need to change any values ​​in the original array if you do not want it. Here is a simple example:

 >>> import numpy as np >>> a = np.arange(1,10).reshape(3,3) >>> b = a.astype(bool) >>> b[1:2,1:2] = False >>> b array([[ True, True, True], [ True, False, True], [ True, True, True]], dtype=bool) >>> a[b] array([1, 2, 3, 4, 6, 7, 8, 9]) 
+6
source

You can replace the middle region with some placeholder value (I used -12345, everything that cannot happen in your actual data will work), then select everything that is not equal to this value:

 >>> import numpy as np >>> a = np.arange(1,26) >>> a.shape = (5,5) >>> a array([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]) >>> a[1:4,1:4] = -12345 >>> a array([[ 1, 2, 3, 4, 5], [ 6, -12345, -12345, -12345, 10], [ 11, -12345, -12345, -12345, 15], [ 16, -12345, -12345, -12345, 20], [ 21, 22, 23, 24, 25]]) >>> a[a != -12345] array([ 1, 2, 3, 4, 5, 6, 10, 11, 15, 16, 20, 21, 22, 23, 24, 25]) 

If you use a float array and not an integer array, you can do it a bit more elegantly using NaN and isfinite :

 >>> a = np.arange(1,26).astype('float32') >>> a.shape = (5,5) >>> a[1:4,1:4] = np.nan >>> a array([[ 1., 2., 3., 4., 5.], [ 6., nan, nan, nan, 10.], [ 11., nan, nan, nan, 15.], [ 16., nan, nan, nan, 20.], [ 21., 22., 23., 24., 25.]], dtype=float32) >>> a[np.isfinite(a)] array([ 1., 2., 3., 4., 5., 6., 10., 11., 15., 16., 20., 21., 22., 23., 24., 25.], dtype=float32) 
+2
source

Source: https://habr.com/ru/post/918597/


All Articles