How can I perform the "reverse" of numpy argwhere? [duplicate] - python

This question already has an answer here:
Replace 2D numpy array elements based on 2D indexes [duplicate]
(1 answer)
Closed 12 months ago.
Suppose I have a boolean numpy array, and I perform np.argwhere() on it. Is there any way to easily and efficiently do the reverse operation? In other words, given the final shape of a, and the results of argwhere(), how can I find a? I've tried to use the argwhere results together with an array full of False, but can't figure out how to use to do it. Maybe somehow use np.where()?
>>> a = np.array([[False, True, False, True, False],
[False, False, True, False, False]])
>>> results = np.argwhere(a)
>>> results
array([[0, 1],
[0, 3],
[1, 2]], dtype=int64)
>>> recover_a = np.full(shape=a.shape, fill_value=False) # I am
>>> # guessing I could start here then do something...

Use results columns as indices to update the value in recover_a:
recover_a[results[:,0], results[:,1]] = True
recover_a
# array([[False, True, False, True, False],
# [False, False, True, False, False]])

In [233]: a = np.array([[False, True, False, True, False], [False, False, True,
...: False, False]])
In [234]: np.argwhere(a)
Out[234]:
array([[0, 1],
[0, 3],
[1, 2]])
In [235]: np.nonzero(a)
Out[235]: (array([0, 0, 1]), array([1, 3, 2]))
argwhere is just the np.transpose(np.nonzero(a)). One is a tuple of arrays, the other a 2d array with those arrays arranged as columns.
The nonzero/where result is better for indexing, since it is a tuple of indices.
In [236]: res = np.zeros(a.shape, bool)
In [237]: res[np.nonzero(a)] = True
In [238]: res
Out[238]:
array([[False, True, False, True, False],
[False, False, True, False, False]])
In [239]: a[np.nonzero(a)]
Out[239]: array([ True, True, True])

Related

Mask an 2Darray row wise by another array

Consider the following 2d array:
>>> A = np.arange(2*3).reshape(2,3)
array([[0, 1, 2],
[3, 4, 5]])
>>> b = np.array([1, 2])
I would like to get the following mask from A as row wise condition from b as an upper index limit:
>>> mask
array([[True, False, False],
[True, True, False]])
Can numpy do this in a vectorized manner?
You can use array broadcasting:
mask = np.arange(A.shape[1]) < b[:,None]
output:
array([[ True, False, False],
[ True, True, False]])
Another possible solution, based on the idea that the wanted mask corresponds to a boolean lower triangular matrix:
mask = np.tril(np.ones(A.shape, dtype=bool))
Output:
array([[ True, False, False],
[ True, True, False]])

Get 2d np.array row indices depending on other 2d np.array

I want to fetch all row indicies of an 2d np.array on the basis of another 2d np.array.
Input:
all_elements = np.array([[1, 1], [2, 2], [3, 3]])
elements = np.array([[1, 1],[2, 2]])
Something like:
idx = np.row_idx(elements, all_elements, axis=0)
output:
[0, 1]
I have been trying to do this with some version of np.where(np.isin(.....)) but i can't get it to work properly.
Any1 have any tips?
IIUC, you might want to use:
np.where((all_elements==elements[:,None]).all(2).any(0))[0]
output: array([0, 1])
explanation:
# compare all elements using broadcasting
(all_elements==elements[:,None])
array([[[ True, True],
[False, False],
[False, False]],
[[False, False],
[ True, True],
[False, False]]])
# all True on the last dimension
(all_elements==elements[:,None]).all(2)
array([[ True, False, False],
[False, True, False]])
# any match per first dimension
(all_elements==elements[:,None]).all(2).any(0)
array([ True, True, False])

How can I use numpy array elements as indices to assign values for another numpy array

I have following problem, which I want to solve using numpy array elements.
The problem is:
Matrix = np.zeros((4*4), dtype = bool) which gives this 2D matrix.
Matrix = [[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False]]
Les us suppose that we have an another array a = np.array([0,1], [2,1], [3,3])
a = [[0, 1],
[2, 1],
[3, 3]]
My question is: How to use the elements of the a array as indices to fill my matrix with True's. The output should seem like this
Matrix = [[False, True, False, False], # [0, 1]
[False, False, False, False],
[False, True, False, False], # [2, 1]
[False, False, False, True]] # [3, 3]
import numpy as np
Matrix = np.zeros((4*4), dtype = bool).reshape(4,4)
a = [[0, 1],
[2, 1],
[3, 3]]
Unroll them into a proper pair of indexing arrays for a 2d array
a = ([x[0] for x in a], [x[1] for x in a])
Matrix[a] = True
>>> Matrix
array([[False, True, False, False],
[False, False, False, False],
[False, True, False, False],
[False, False, False, True]])
Simple way to make the (4,4) bool array:
In [390]: arr = np.zeros((4,4), dtype = bool)
In [391]: arr
Out[391]:
array([[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False]])
Proper syntax for making a:
In [392]: a = np.array([[0,1], [2,1], [3,3]])
In [393]: a
Out[393]:
array([[0, 1],
[2, 1],
[3, 3]])
Use the 2 columns of a as indices for the 2 dimensions of arr:
In [394]: arr[a[:,0],a[:,1]]=True
In [395]: arr
Out[395]:
array([[False, True, False, False],
[False, False, False, False],
[False, True, False, False],
[False, False, False, True]])

Compare columns of numpy matrix with array

I have a numpy matrix and want to compare every columns to a given array, like:
M = np.array([1,2,3,3,2,1,1,3,2]).reshape((3,3)).T
v = np.array([1,2,3])
Now I want to compare every columns of M with v, i.e. I want a matrix with the first column consisting of True, True, True. A second saying False, True, False. A third True, False, False.
How do I achieve this?
Thanks!
Use broadcasted comparison:
>>> M == v[:, None]
array([[ True, False, True],
[ True, True, False],
[ True, False, False]])
You might consider using np.equal column-wise:
np.array([np.equal(col, v) for col in M.T]).T
it compares the elements of two numpy arrays element-wise. The M.T makes for loop to pop your original M columns as one-dimensional arrays and the final transpose is needed to reverse it.
Here the equal/not_equal functions are described.
Alternatively, you could match each row in the matrix with the given vector using np.apply_along_axis
>>> M
array([[1, 3, 1],
[2, 2, 3],
[3, 1, 2]])
>>> v
array([1, 2, 3])
>>> np.apply_along_axis(lambda x: x==v, 1, M)
array([[ True, False, False],
[False, True, True],
[False, False, False]], dtype=bool)

Acces all off diagonal elements of boolean numpy matrix

Suppose there is a diagonal matrix M:
#import numpy as np
M = np.matrix(np.eye(5, dtype=bool))
Does anybody know a simple way to access all off diagonal elements, meaning all elements that are False? In R I can simply do this by executing
M[!M]
Unfortunately this is not valid in Python.
You need the bitwise not operator:
M[~M]
You might try np.extract combined with np.eye. For example:
M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
np.extract(1 - np.eye(3), M)
# result: array([2, 3, 4, 6, 7, 8])
In your example it's almost an identity:
M = np.matrix(np.eye(5, dtype=bool))
np.extract(1 - np.eye(5), M)
#result:
array([False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False], dtype=bool)

Categories

Resources