-1

I am trying to find values in an np.array corresponding to an index and then those that are not in the index. In R, I would do

> x <- c(1,2,3,4,5)
> ind = c(1,4)
> x[ind]
[1] 1 4
> x[-ind]
[1] 2 3 5

In Python, I can index and get the values in the index in the following manner

import numpy as np
x = np.array([1,2,3,4,5])
ind = [0,3]
x[ind]

However, in Python how can I get the values NOT in my index as I show in the R code using x[-ind]?

I found the SO post below and have replicated this, but is this indeed the "right" or best approach? NumPy array, change the values that are NOT in a list of indices

Georgy
  • 12,464
  • 7
  • 65
  • 73
user350540
  • 429
  • 5
  • 17
  • What do you mean by "right or best"? Best in terms of what? That answer works, so what else exactly do you want to know? – Georgy Apr 27 '20 at 23:01

2 Answers2

3

I think the most intuitive way would be with np.delete

np.delete(x, ind)

As it gives you back the remainig elements

array([2, 3, 5])
Björn
  • 1,610
  • 2
  • 17
  • 37
2

I do not think there is a solution quite as pretty as Rs, but how about

x[~np.isin(np.arange(len(x)), ind)]
modesitt
  • 7,052
  • 2
  • 34
  • 64