如何使用python维护ndarray中数字的出现顺序?

时间:2017-11-22 07:05:33

标签: python python-2.7 pandas numpy set

情景

我正在尝试获取数据帧所属的群集数量。 数据类型为<type 'numpy.ndarray'>,数据如下

records_Array = array([0, 0, 0, 0, 2, 2, 1, 1, 1], dtype=int32)

显然,在打印时我会看到[0 0 0 ..., 1 1 1]这种格式。

现在,我只需要一次数字,所以我转换为set然后转换为List,

cluster_set = list(set(records_Array))

输出

在打印cluster_set时,我得到[0, 1, 2]

  

其中聚类按0, 2, 1

的顺序排列

必需

我需要一些函数/方法,它保留records_Array的序列并返回cluster_set

1 个答案:

答案 0 :(得分:1)

你想要Pandas'pd.unique,因为它没有排序,因为它找到了唯一的值。 Numpy的独特功能确实如此。

a = np.array([0, 0, 0, 0, 2, 2, 1, 1, 1])

pd.unique(a)

array([0, 2, 1])