Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index Python List with Numpy Boolean Array

Tags:

python

numpy

Is there a way to index a python list like x = ['a','b','c'] using a numpy boolean array? I'm currently getting the following error: TypeError: only integer arrays with one element can be converted to an index

like image 656
Apollo Avatar asked Dec 15 '22 02:12

Apollo


1 Answers

Indexing via [] secretly calls the object's __getitem__ method. For objects implemented in pure Python, you can simply overwrite this method with any function which suits your needs. Lists however are implemented in C, so you are not allowed to replace list.__getitem__. Therefore there are no direct way to do what you request.

You can however make a NumPy array out of your list and then do NumPy-style boolean indexing on that:

import numpy as np

x = ['a', 'b', 'c']

mask = np.array([True, False, True])
x_arr = np.asarray(x, dtype=object)
output = x_arr[mask]  # Get items
x_arr[mask] = ['new', 'values']  # Set items

Unfortunately, np.asarray cannot simply make a view over your list, so the list is simply copied. This means that the original x is unchanged when assigning new values to the elements of x_arr.

If you really want the full power of NumPy boolean indexing on lists, you have to write a function which does this from scratch, and you will not be able to use the [] indexing syntax.

like image 52
jmd_dk Avatar answered Dec 30 '22 19:12

jmd_dk