How to return list of items from an array given list on indices in numpy

YohanRoth

I have an array arr and a list of indices that I want to get indices. I want to get subset of array corresponding to items in indices and the complement of that.

For example

for

arr = np.asarray([2, 4, 1, 5, 6])
indices = np.asarray([2, 4])

I would get

[1, 6] and [2, 4, 5]

Thanks

Mstaino

Using np.isin or np.in1d (using masks):

arr = np.asarray([2, 4, 1, 5, 6])
indices = np.asarray([2, 4])
m = np.in1d(np.arange(len(arr)), indices)
arr1, arr2 = arr[m], arr[~m]
arr1, arr2
>>array([1, 6]), array([2, 4, 5])

Alternatively, using np.setdiff1d for the complementary part (can be faster for larger arrays and indices):

arr1 = arr[indices]
arr2 = arr[np.setdiff1d(np.arange(len(arr)), indices, True)]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Return the maximum level of nesting and list of items at a given level from the given JSON

How to get the indices list of all NaN value in numpy array?

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

Get indices of items in numpy array, where values is in list

How to get a list of all indices of repeated elements in a numpy array?

Find indices of a list of values in a not sorted numpy array

How to remove a list of indices from list

How to check if a list of numpy arrays contains a given test array?

Vectorized solution to filling a 1-D numpy array given a list of start and end indices for slicing?

Stack slices of numpy array from given indices

Build 2D numpy array from items in list of tuples

How to return list of indices that contain value

From numpy array, get indices of values list

how to pupulate dropdown list with items from array?

Removing items from list given a list of indices where items occur - Haskell

Remove leading None items from a Numpy array or Python List

How to index with list of indices in a multidimensional array in numpy/pytorch

How do I a generate a list of edges from a given list of vertex indices?

How to fill an array in python with given list of values and list of indices?

How to slice a numpy array by a list of column indices

Given a list, How to count items in that list?

sum numpy array at given indices

Finding indices of items from a list in another list even if they repeat

Return values of a list for specific list of indices from another list

Return a sorted list of indices from list of lists

Given a 3D image array, return a list of indices with a value above a threshold and a minimum distance between all selected indices?

Given the output of numpy.where(), how to acquire a list of list of the indices

Numpy restrict array to given indices

Is there a numpy way to filter an array of arrays by a list of indices