1 回答

TA貢獻1804條經驗 獲得超7個贊
axis=0
對于列表列表,您可以通過使用選項(指定行)以及numpy.unique()
函數和選項來獲取行數return_counts=True
:
>>> a = np.array([(1,2,3),(1,2,3),(3,4,5),(5,6,7)])
>>> np.unique(a, return_counts=True, axis=0)
(array([[1, 2, 3],
? ? ? ?[3, 4, 5],
? ? ? ?[5, 6, 7]]), array([2, 1, 1]))
第一個返回值是唯一行,第二個返回值是這些行的計數。如果沒有該return_counts=True選項,您將只能獲得第一個返回值。如果沒有該axis=0選項,整個數組將被展平以計算唯一元素的數量。axis=0指定應展平行(如果它們已經超過 1D),然后將其視為唯一值。
如果您可以使用元組而不是行列表,那么您可以numpy.unique()與 axis 選項一起使用。
這篇文章解釋了如何使用 numpy 數組的元組列表。
放在一起,它應該看起來像這樣:
>>> l = [(1,2,3),(1,2,3),(3,4,5),(5,6,7)]
>>> a = np.empty(len(l), dtype=object)
>>> a
array([None, None, None, None], dtype=object)
>>> a[:] = l
>>> a
array([(1, 2, 3), (1, 2, 3), (3, 4, 5), (5, 6, 7)], dtype=object)
>>> np.unique(a, return_counts=True)
(array([(1, 2, 3), (3, 4, 5), (5, 6, 7)], dtype=object), array([2, 1, 1]))
添加回答
舉報