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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With