[PYTHON] Extract elements other than a specific index with Numpy

If you are an R user, the following operations are as common as breathing. With this, the elements excluding specific subscripts can be extracted.

vec <- 1:10
ind_rm <- c(5, 7)
# ind_Extracting elements by specifying an index other than rm
print(vec[-ind_rm])
[1]  1  2  3  4  6  8  9  10

Unexpectedly, I can't think of a smart way to do it with numpy. I think everyone is in trouble. I'm sad if I'm the only one.

I want to do it with Numpy

After all, the idea of something other than a specific element like R seems to be wrong in the first place, so let's think about how to make an array or list that includes the subscripts of the elements to be left obediently.

If I do it obediently, I feel like this, but I can't wipe out the feeling that something ʻin` or something is obviously uselessly calculated.

import numpy as np

vec = np.arange(10)
ind_rm = [5, 7]

# [0, 1, 2, 3, 4, 6, 8, 9]Want to make!
ind = [i for i in range(10) if i not in ind_rm]

print vec[ind]

Check with Stack overflow I was a little impressed with the following method.

import numpy as np

vec = np.arange(10)
ind_rm = [5, 7]

# [True, True, True, True, False, True, False, True, True, True]Policy to make
ind = np.ones(10, dtype=bool)
ind[ind_rm] = False

print vec[ind]

It doesn't save the number of lines, but it seems to be a little faster because there is no useless calculation. I first learned that np.ones has such a usage.

Summary

Looking for a better way.

Recommended Posts

Extract elements other than a specific index with Numpy
How to extract other than a specific index with Numpy
Extract multiple elements with Numpy array
Extract non-numeric elements with pandas.DataFrame
Extract array elements and indexes in descending order with numpy
Enumerate files with a specific extension
Draw a beautiful circle with numpy
[Python] How to get a value with a key other than value with Enum
Extract specific multiple columns with pandas
Generate all files with a specific extension
I made a life game with Numpy
Read a character data file with numpy
Send an email with a user other than EMAIL_HOST_USER written in settings in django
Extract elements (using a list of indexes) in a NumPy style from a Python list / tuple
Find a position above the threshold with NumPy
Clone with a specific branch / tag in GitPython
Extract lines containing a specific "string" in Pandas
Sort dict in dict (dictionary in dictionary) with a specific key
I made a random number graph with Numpy
Extract data from a web page with Python
[Python] I want to add a static directory with Flask [I want to use something other than static]
[Python] Leave only the elements that start with a specific character string in the array
Python2 / numpy> Replace only a specific column in a file with column data from another file> numpy.c_