python - 有没有一种优雅的方法来检查数组中的哪些元素位于另一个容器中?

标签 python arrays numpy

我确信相同或类似的问题已经被问过很多次了,但也许我的措辞有问题,所以我还没有找到合适的帖子。

这是一个例子:

import numpy as np


students = np.array(
    [('Jim', 2), ('John', 3), ('Lisa', 5), ('Laura', 1)],
    dtype=[('name', 'O'), ('grade', 'i4')]
)

# this works
good_students = students[students['grade'] < 3]

# this doesn't because unfortunately, numpy doesn't understand that I want 
# it to do elementwise comparison
# absent_students = students[students['name'] in ['John', 'Laura']]

# this does but is ugly
absent_students = np.array(
    [], dtype=[('name', 'O'), ('grade', 'i4')]
)
for name in ['John', 'Laura']:
    absent_students = np.append(
        absent_students, students[students['name'] == name]
    )

有没有比手动循环容器更好的方法?

最佳答案

使用np.isin :

absent_students = students[np.isin(students['name'],['John', 'Laura'])]
print(absent_students)

输出

[('John', 3) ('Laura', 1)]

作为替代方案,扁平版本 np.in1d :

absent_students = students[np.in1d(students['name'],['John', 'Laura'])]
print(absent_students)

输出

[('John', 3) ('Laura', 1)]

更新

请注意,如果 test_elements(即 ['John', 'Laura'])是一个集合,则此方法将不起作用。来自文档:

If test_elements is a set (or other non-sequence collection) it will be converted to an object array with one element, rather than an array of the values contained in test_elements. This is a consequence of the array constructor’s way of handling non-sequence collections. Converting the set to a list usually gives the desired behavior.

关于python - 有没有一种优雅的方法来检查数组中的哪些元素位于另一个容器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65215989/

相关文章:

python - 如何使用 kinterbasdb 运行 DDL 脚本

java - 带轴 JTable

arrays - (F#) 查找二维数组中元素的索引

python - Jupyter notebook 选择旧版本的 numpy

java - apache poi 与 python xlrd

python - 这个 lambda 函数有什么作用?

python - 在AI Platform (CMLE)上使用tensorflow_dataset库

python - 翻转和旋转 numpy 数组以绘制等高线图

python - NumPy 中向量的叉积

python - numpy 在进行矩阵乘法时是否使用内存中的空间局部性?