如何在Python中使用MATLAB的唯一值(a,'rows')? [英] How can I use the unique(a, 'rows') from MATLAB in Python?
问题描述
我正在将一些东西从MATLAB转换为Python语言.
I'm translating some stuff from MATLAB to the Python language.
在 NumPy 中有一个唯一的命令.但是由于MATLAB程序也运行行"命令,所以它提供了一些不同的地方.
There's this command, unique(a), in NumPy. But since the MATLAB program runs the 'rows' command also, it gives something a little different.
Python中是否有类似的命令,或者我应该做一些能做同样事情的算法?
Is there a similar command in Python or should I make some algorithm that does the same thing?
推荐答案
假设您的2D数组以通常的C顺序存储(也就是说,每一行都被视为主数组中的一个数组或列表;换句话说,行优先顺序),或者事先转置数组,否则,您可以执行类似...
Assuming your 2D array is stored in the usual C order (that is, each row is counted as an array or list within the main array; in other words, row-major order), or that you transpose the array beforehand otherwise, you could do something like...
>>> import numpy as np
>>> a = np.array([[1, 2, 3], [2, 3, 4], [1, 2, 3], [3, 4, 5]])
>>> a
array([[1, 2, 3],
[2, 3, 4],
[1, 2, 3],
[3, 4, 5]])
>>> np.array([np.array(x) for x in set(tuple(x) for x in a)]) # or "list(x) for x in set[...]"
array([[3, 4, 5],
[2, 3, 4],
[1, 2, 3]])
当然,如果您需要按其原始顺序排列唯一行,那么这实际上是行不通的.
Of course, this doesn't really work if you need the unique rows in their original order.
顺便说一句,要模拟类似unique(a, 'columns')
的内容,您只需转置原始数组,执行上面显示的步骤,然后再转回.
By the way, to emulate something like unique(a, 'columns')
, you'd just transpose the original array, do the step shown above, and then transpose back.
这篇关于如何在Python中使用MATLAB的唯一值(a,'rows')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!