Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical vector as index in Python?

Tags:

python

indexing

r

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]
>>> ???
like image 996
Ricardo Saporta Avatar asked Mar 30 '26 23:03

Ricardo Saporta


1 Answers

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')
like image 80
Prashant Kumar Avatar answered Apr 02 '26 03:04

Prashant Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!