【问题标题】:Logical vector as index in Python?逻辑向量作为Python中的索引?
【发布时间】:2013-12-10 19:00:52
【问题描述】:

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]
>>> ???

【问题讨论】:

    标签: python r indexing


    【解决方案1】:

    不过,在纯 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')
    

    【讨论】:

    • 如果您将数据分析平台从 R 更改为 Python,那么无论如何您都希望使用 Numpy+Pandas+Matplotlib。
    【解决方案2】:

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

    【讨论】:

    • 我从来没有用过很多R,但我不确定OP是否正在寻找掩码数组或者OP是否正在寻找boolean indexing
    • @mgilson,你链接到的实际上正是我要找的
    • @RicardoSaporta -- 很高兴为您提供帮助 :)
    • @mgilson:好点!我用一个布尔索引示例更新了我的答案。
    猜你喜欢
    • 2021-10-01
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2014-04-17
    • 1970-01-01
    相关资源
    最近更新 更多