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

Ric*_*rta 3 python indexing r

我们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]
>>> ???
Run Code Online (Sandbox Code Playgroud)

Pra*_*mar 5

不过,在纯 Python 中,你可以尝试这个

[x for x, y in zip(LL, ind) if y]
Run Code Online (Sandbox Code Playgroud)

如果indLL是 Numpy 数组,那么你可以LL[ind]像在 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')
Run Code Online (Sandbox Code Playgroud)

  • 如果您要将数据分析平台从 R 更改为 Python,无论如何您都希望使用 Numpy+Pandas+Matplotlib。 (4认同)