Ricardo Saporta
Ricardo Saporta

Reputation: 55390

Logical vector as index in Python?

In R we can use a logical vector as an index to another vector or list.
Is there an analogous syntax in Python?

## In R:
R> LL  = c("A", "B", "C")
R> ind = c(TRUE, FALSE, TRUE)
R> LL[ind]
[1] "A" "C"

## In Python
>>> LL = ["A", "B", "C"]
>>> ind = [True, False, True]
>>> ???

Upvotes: 3

Views: 886

Answers (2)

mdml
mdml

Reputation: 22902

If you can use third-party modules, check out Numpy, specifically masked arrays:

>>> import numpy as np
>>> LL = np.array(["A", "B", "C"])
>>> ind = np.ma.masked_array([True, False, True])
>>> LL[ind]
array(['A', 'C'], 
      dtype='|S1')

or boolean indexing (helpfully pointed out by @mgilson):

>>> # find indices where LL is "A" or "C"
>>> ind = np.array([True, False, True])
>>> LL[ind]
array(['A', 'C'], 
      dtype='|S1')

Upvotes: 4

Prashant Kumar
Prashant Kumar

Reputation: 22579

In pure Python, though, you might try this

[x for x, y in zip(LL, ind) if y]

If ind and LL are Numpy arrays, then you can go LL[ind] just like in R.

import numpy as np

LL = np.array(["A", "B", "C"])
ind = np.array([True, False, True])

LL[ind]    # returns array(['A', 'C'], dtype='|S1')

Upvotes: 5

Related Questions