python - 在 python 中对数组使用多个索引

标签 python arrays indexing numpy

我有一个关于如何为数组或 rec.array 使用多个索引的简单问题。更具体地说,我想隔离满足多个规定的数组中的单元格。例如:

import numpy as np
test = np.ones(5)
test_rec = test.view(recarray)
test_rec.age = np.array([0,1,2,1,4])
test_rec.sex = np.array([0,1,1,0,0])

我想隔离 test_rec,其中 test_rec 年龄为 1 且 test_rec.sex 为 1,即:

test_rec[test_rec.age==1 and test_rec.sex==1]

不幸的是,这不起作用。

最佳答案

使用 logical_and() 或 bitwise_and(),您可以使用 & 运算符来执行 bitwise_and():

test_rec[(test_rec.age==1) & (test_rec.sex==1)]

括号很重要,因为 & 的优先级低于 ==。

关于python - 在 python 中对数组使用多个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6936344/

相关文章:

python - App Engine 后端配置 (python)

Javascript 检查重复项并添加重复的 id

c - 填充数组的机制

python - 从系列更改索引创建 Pandas 数据框

python - 将重复行添加到 DataFrame

python - 如何确保我的 Python 正则表达式输出字典?

ios - Swift - 如何检查 map 注释(pin)是否在数组内?

python - 使用 zip 和 np.insert 将零部分插入 numpy 数组

performance - 具有多个相同列索引的 Oracle 性能

python - json.load() 和 json.loads() 函数有什么区别