什么是'in` numpy数组[重复]是什么意思(what does it mean to be `in` numpy array [duplicate])

编程入门 行业动态 更新时间:2024-10-21 15:44:51
什么是'in` numpy数组[重复]是什么意思(what does it mean to be `in` numpy array [duplicate])

这个问题在这里已有答案:

__contains__如何为ndarrays工作? 2个答案

我有一些代码,我希望它能做到这一点:

>> x=np.zeros((40,2)) >> x[31]=(12,15) >> y=x.copy() >> y[31]=(12,4) #the following behavior is correct, but the syntax is unwieldy with the #conversions to float and list, quite annoying >> e=[12.,15.] >> e in x.tolist() True >> e in y.tolist() False

但是,在调试过程中我发现了以下奇怪的行为:

>> e in x True >> e in y True

即使

>> f=(8,93) >> f in x False

我的问题有两个:

a)numpy在这里做什么来产生这个结果?

b)除了使用tolist和float转换之外,还有其他方法可以完成此检查(不使用python级别for循环)吗? 这种设计不明显,不易维护。

This question already has an answer here:

How does __contains__ work for ndarrays? 2 answers

I have some code, and what I would like it to do is this:

>> x=np.zeros((40,2)) >> x[31]=(12,15) >> y=x.copy() >> y[31]=(12,4) #the following behavior is correct, but the syntax is unwieldy with the #conversions to float and list, quite annoying >> e=[12.,15.] >> e in x.tolist() True >> e in y.tolist() False

However, in the course of debugging I observed the following odd behavior:

>> e in x True >> e in y True

even though

>> f=(8,93) >> f in x False

My question is twofold:

a) What is numpy doing here to produce this result?

b) Is there some way to accomplish this check other than using tolist and float conversion as I have here (without using a python-level for loop)? This design is not obvious and not easily maintainable.

最满意答案

认为 in会给你一个相当于np.any(y == e) ,其中维度是自动广播的。 如果你看y == e (粘贴在这个答案的底部)它有一个True元素。 比我更了解情况的人会知道究竟发生了什么。

可能有一种更简洁的方法,但我建议这样做而不是转换为列表:

>>> np.any(np.all(x == e, axis=-1)) True >>> np.any(np.all(y == e, axis=-1)) False

输出y == e看起来像

>>> y == e array([[False, False], ... [False, False], [ True, False], [False, False], ... [False, False]], dtype=bool)

I think that in will give you a result equivalent to np.any(y == e) where the dimensions are broadcasted automatically. If you look at y == e (pasted at the bottom of this answer) it has a single True element. Someone more knowledgeable than me will know what's really going on.

There is probably a cleaner way to do it but I would suggest this instead of converting to a list:

>>> np.any(np.all(x == e, axis=-1)) True >>> np.any(np.all(y == e, axis=-1)) False

Output of y == e looks like

>>> y == e array([[False, False], ... [False, False], [ True, False], [False, False], ... [False, False]], dtype=bool)

更多推荐

本文发布于:2023-07-25 05:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1256764.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   numpy   duplicate   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!