What does np.r_ (numpy) do?

The following code is taken from here

sa = sort(a[i:i+block]) n += np.r_[sa.searchsorted(bins[:-1], 'left'), sa.searchsorted(bins[-1], 'right')] 

So, I know that searchsorted finds the position in the sa array where the bins must be inserted to preserve the sa sort ( left gives the index to the left of where we insert the value and right right index). What I do not understand is the whole structure around it, which means

 np.r_[array,array] 

What is np.r_ ?

+19
python numpy
source share
2 answers

What he does is mix the strings. There is a good example in this post :

 >>>V = array([1,2,3,4,5,6 ]) >>>Y = array([7,8,9,10,11,12]) >>>np.r_[V[0:2],Y[0],V[3],Y[1:3],V[4:],Y[4:]] array([ 1, 2, 7, 4, 8, 9, 5, 6, 11, 12]) 

Read more about this in the numpy documentation .

+24
source share
 numpy.r_[array[], array[]] 

This is used to combine any number of slices of the array along the axis of the (first) row. This is an easy way to quickly and efficiently create arrays.

For example, to create an array of two different arrays by selecting the elements of your choice, we will need to assign the sliced ​​values ​​to the new varaible and use the concatenation method to connect them along the axis.

 >>> a = np.arange(9).reshape(3,3) >>> b = np.arange(10,19).reshape(3,3) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> b array([[10, 11, 12], [13, 14, 15], [16, 17, 18]]) 

I want to create a new 2-D array with 2 * 2 elements ([4,5,14,15]), then I have to do the following,

 >>> slided_a = a[1,1:3] >>> sliced_b = b[1,1:3] >>> new_array = np.concatenate((sliced_a, sliced_b), axis = 0) 

Since this is clearly an inefficient method, as with the increase in the number of elements to be included in the new array, the temporary variables that are assigned to store the selected values ​​increase.

Here we use np.r_

 >>> c = np.r_[a[1,1:3],b[1,1:3]] array([ 4, 5, 14, 15]) 

Similarly, if we want to create a new array by adding the sliced ​​values ​​along the 2nd axis, we can use np.c_

 >>> c = np.c_[a[1,1:3],b[1,1:3]] array([[ 4, 14], [ 5, 15]]) 
+1
source share

All Articles