逻辑向量作为Python中的索引?

时间:2013-12-10 19:00:52

标签: python r indexing

R中,我们可以使用逻辑向量作为另一个向量或列表的索引 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]
>>> ???

2 个答案:

答案 0 :(得分:4)

但是在纯Python中,你可以试试这个

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

如果indLL是Numpy数组,那么就像在R中一样LL[ind]

import numpy as np

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

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

答案 1 :(得分:3)

如果您可以使用第三方模块,请查看Numpy,特别是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')

boolean indexing(由@mgilson帮助指出):

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