Test existence of subarray in ndarrray [duplicate] - python

This question already has answers here:
testing whether a Numpy array contains a given row
(5 answers)
Closed 1 year ago.
For a numpy array of shape (n, 2), n points with 2 coordinates, what is the best way (fastest for large n) to test if a particular point is already in the array. E.g.
test_point = np.array([1, 2])
array_A = array([[1, 3], [2, 2], [2, 1]]) # test on this should return False
array_B = array([[1, 2], [2, 2], [2, 1]]) # test on this should return True

(array_A == test_point).all(axis=1).any()
Explanation:
array_A == test_point applies broadcasting rules and returns array of booleans with shape equal to array_A.
.all(axis=1) returns True for rows if all values are True
.any() returns True if any value in column is True

Kindly verify if this is what you were anticipating:
import numpy as np
test = np.array([1,2])
sample = np.array([[1, 2], [2, 2]])
result = any([all(sample[i,:] == test) for i in range(sample.shape[0])])

Related

finding the minimum value in an array with returned values [duplicate]

This question already has answers here:
How to return all the minimum indices in numpy
(5 answers)
Closed 1 year ago.
I have an array for example:
[1 2 3 4
2 3 4 0
5 4 0 6]
And I want to find the indexes of all the values that are closer to to the value 3.9 (in my example,4)
I tried using :
import numpy as np
def find_nearest(array, value):
idx = (np.abs(array - value)).argmin()
and
np.where(array== array.min())
but none of the options gives me the correct answer.
I do excpect to get:
(3,1),(1,2),(2,1)
In my original code, I iterate an array with the shape of 3648X5472 so "FOR" loops might be too heavy.
hope to get some help here, thank you
You can use:
a = np.array([[1, 2, 3, 4],
[2, 3, 4, 0],
[5, 4, 0, 6]])
v = 3.9
b = abs(a-v)
xs, ys = np.where(b == np.min(b))
output:
>>> xs
array([0, 1, 2])
>>> ys
array([3, 2, 1])
Alternative output:
>>> np.c_[np.where(b == np.min(b))]
array([[0, 3],
[1, 2],
[2, 1]])
# or
>>> np.argwhere(b==np.min(b))
You are pretty close. When you found the index of the first closest value, you can find indices of the equal values with `np.argwhere:
closest = array[np.abs(array - value).argmin()]
np.argwhere(array == closest)

add numpy subarray to numpy array based on condition

I have a 2d numpy array and a 2d numpy subarray that I want to add to the original array based on a condition.
I know that you can add the 2d subarray to the array like this:
original_array[start_x:end_x, start_y:end_y] = sub_array
but I dont know how to efficiently add only values of the sub_array that are bigger than 0?
Example:
orginal_array = np.array([2,2],[2,2],[2,2],[2,2])
sub_array = np.array([0,0],[1,1],[0,1],[0,0])
expected_result = np.array([2,2], [1,1], [2,1], [2,2])
You can index based on the condition >,< 0 and add the arrays.
orginal_array * (sub_array <= 0) + sub_array * (sub_array > 0)
array([[2, 2],
[1, 1],
[2, 1],
[2, 2]])
Another approach is to use the np.where function as:
np.where(sub_array > 0, sub_array, original_array)
Output:
array([[2, 2],
[1, 1],
[2, 1],
[2, 2]])
Try,
sub_array2 = np.select([sub_array>0],[sub_array])
original_array[start_x:end_x, start_y:end_y] = sub_array2

How to extend an numpy array with two index array [duplicate]

This question already has answers here:
Indexing one array by another in numpy
(4 answers)
Closed 3 years ago.
I have an numpy matrix, for example:
a = np.array([[1, 2], [3, 4]])
Then, I want to use another numpy matrix with indexes to extend the matrix, for example:
idxes = np.array(([0, 1, 0], [1, 0, 1]]) # the indexes matrix
The operation is like:
result = a[:, idxes] # this is an wrong expression
The result I expected is:
>>result
array([[1, 2, 1],
[4, 3, 4]])
I want to know how to do that.
You'll need to specify the a range for the first (0th) axis.
a[np.arange(len(a))[:,None], idxes]
This intuitively follows the indexing operation, the first row of idxes will index into the first row of a, the second row of idxes will index the second row of a, and so on.
Additionally, the dimensions of arange array need to be expanded from 1D to 2D because idxes is also a 2D array.
A fun way diagonal + take, diagonal here make sure you always slice the row index equal to the columns index items , which will return the just like row-wise out put
np.diagonal(np.take(a, idxes,1)).T
array([[1, 2, 1],
[4, 3, 4]])
Or
np.diagonal(a[:,idxes]).T
array([[1, 2, 1],
[4, 3, 4]])

best way to create numpy array from FOR loop [duplicate]

This question already has answers here:
Cartesian product of x and y array points into single array of 2D points
(17 answers)
Closed 6 months ago.
Is there a better way to create a multidimensional array in numpy using a FOR loop, rather than creating a list? This is the only method I could come up with:
import numpy as np
a = []
for x in range(1,6):
for y in range(1,6):
a.append([x,y])
a = np.array(a)
print(f'Type(a) = {type(a)}. a = {a}')
EDIT: I tried doing something like this:
a = np.array([range(1,6),range(1,6)])
a.shape = (5,2)
print(f'Type(a) = {type(a)}. a = {a}')
however, the output is not the same. I'm sure I'm missing something basic.
You could preallocate the array before assigning the respective values:
a = np.empty(shape=(25, 2), dtype=int)
for x in range(1, 6):
for y in range(1, 6):
index = (x-1)*5+(y-1)
a[index] = x, y
Did you had a look at numpy.ndindex? This could do the trick:
a = np.ndindex(6,6)
You could have some more information on Is there a Python equivalent of range(n) for multidimensional ranges?
You can replace double for-loop with itertools.product.
from itertools import product
import numpy as np
np.array(list(product(range(1,6), range(1,6))))
For me creating array from list looks natural here. Don't know how to skip them in that case.
Sometimes it is difficult to predict the total element number and shape at stage of selecting array elements due to some if statement inside a loop.
In this case, put all selected elements in flat array:
a = np.empty((0), int)
for x in range(1,6): # x-coordinate
for y in range(1,6): # y-coordinate
if x!=y: # `if` statement
a = np.append(a, [x, y])
Then, given the lengths of one array dimension (in our case there are 2 coordinates) one can use -1 for the unknown dimension:
a.shape = (-1, 2)
a
array([[1, 2],
[1, 3],
[1, 4],
[1, 5],
[2, 1],
[2, 3],
[2, 4],
[2, 5],
[3, 1],
[3, 2],
[3, 4],
[3, 5],
[4, 1],
[4, 2],
[4, 3],
[4, 5],
[5, 1],
[5, 2],
[5, 3],
[5, 4]])

How to work with numpy.where? [duplicate]

This question already has an answer here:
Matching an array to a row in Numpy
(1 answer)
Closed 5 years ago.
I want to find indexes of array like x = np.array([[1, 1, 1], [2, 2, 2]]) where elements equals to y = np.array([1, 1, 1]). So I did this:
In: np.where(x == y)
Out: (array([0, 0, 0]), array([0, 1, 2]))
It is the correct answer. But I expect to get only index 0 because the zero element of x is equal to y.
You need to use (x == y).all(axis=1) to reduce the comparison result over axis=1 first, i.e all elements are equal:
np.where((x == y).all(axis=1))[0]
# array([0])

Categories

Resources