从numpy的矩阵构建一套巨蟒

从numpy的矩阵构建一套巨蟒

本文介绍了从numpy的矩阵构建一套巨蟒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图执行以下

>> from numpy import *
>> x = array([[3,2,3],[4,4,4]])
>> y = set(x)
TypeError: unhashable type: 'numpy.ndarray'

我怎么能轻松高效地从numpy的阵列创建一组?

How can I easily and efficiently create a set from a numpy array?

推荐答案

如果你想要一组元素,这里是另一个,可能是更快的方式:

If you want a set of the elements, here is another, probably faster way:

y = set(x.flatten())

PS: x.flat x.flatten之间进行比较()和<$ C $之后C> x.ravel() A 10x100阵列上,我发现他们都在大致相同的速度执行。对于一个3x3的阵列,最快的版本是迭代器版本:

PS: after performing comparisons between x.flat, x.flatten(), and x.ravel() on a 10x100 array, I found out that they all perform at about the same speed. For a 3x3 array, the fastest version is the iterator version:

y = set(x.flat)

我会建议,因为它是较少的内存便宜的版本(它扩展了很好的数组的大小)。

which I would recommend because it is the less memory expensive version (it scales up well with the size of the array).

PS :还有一个numpy的功能,做类似的事情:

PS: There is also a NumPy function that does something similar:

y = numpy.unique(x)

这确实产生numpy的阵列相同的元素为集(x.flat),但作为一个numpy的数组。这是非常快的(几乎10倍快),但如果你需要一个设置,然后做设置(numpy.unique(X))比其他程序慢一点(建造了一套带有一个大的开销)。

This does produce a NumPy array with the same element as set(x.flat), but as a NumPy array. This is very fast (almost 10 times faster), but if you need a set, then doing set(numpy.unique(x)) is a bit slower than the other procedures (building a set comes with a large overhead).

这篇关于从numpy的矩阵构建一套巨蟒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:24