在Python2.7中,^{}应该可以工作。(由于对象数组中的混合类型,numpy.unique在Python3中不起作用;请参阅下面的解决方法。)例如,在下面,values是一个数组,其中包含a中的唯一值,counts是一个相应的数组,其中包含该值在a中出现的次数。在In [31]: a
Out[31]:
array([[123, '40381', 'V5856', 0.0],
[456, '40381', '25081', 0.0],
[789, 'V5856', '51851', 0.0]], dtype=object)
In [32]: values, counts = np.unique(a, return_counts=True)
In [33]: values
Out[33]: array([0.0, 123, 456, 789, '25081', '40381', '51851', 'V5856'], dtype=object)
In [34]: counts
Out[34]: array([3, 1, 1, 1, 1, 2, 1, 2])
要按计数降序排列值,请使用counts.argsort()的结果重新排序values和{}:
^{pr2}$
python3的一个解决方法是将数组的所有元素转换为字符串。这是否解决了您的问题取决于您将如何处理np.unique的结果。在
下面是同一个示例,将Python3.4.3与numpy 1.10.1一起使用:In [23]: a
Out[23]:
array([[123, '40381', 'V5856', 0.0],
[456, '40381', '25081', 0.0],
[789, 'V5856', '51851', 0.0]], dtype=object)
In [24]: values, counts = np.unique(a.astype(str), return_counts=True)
In [25]: values
Out[25]:
array(['0.0', '123', '25081', '40381', '456', '51851', '789', 'V5856'],
dtype='
In [26]: counts
Out[26]: array([3, 1, 1, 2, 1, 1, 1, 2])
In [27]: order = counts.argsort()[::-1]
In [28]: values[order]
Out[28]:
array(['0.0', 'V5856', '40381', '789', '51851', '456', '25081', '123'],
dtype='
In [29]: counts[order]
Out[29]: array([3, 2, 2, 1, 1, 1, 1, 1])