NumPy 獲取唯一元素、出現(xiàn)次數(shù)、展平數(shù)組
你好 ,我是 zhenguo
本篇文章介紹2個(gè) NumPy 高頻使用場(chǎng)景,以及對(duì)應(yīng)的API及用法,歡迎學(xué)習(xí)。
1 如何獲得唯一元素和出現(xiàn)次數(shù)
使用np.unique可以很容易地找到數(shù)組中唯一的元素。
例如,如果從這個(gè)數(shù)組開始:
>>> a = np.array([11, 11, 12, 13, 14, 15, 16, 17, 12, 13, 11, 14, 18, 19, 20])
可以使用np.unique打印數(shù)組中的唯一值:
>>> unique_values = np.unique(a)
>>> print(unique_values)
[11 12 13 14 15 16 17 18 19 20]
要獲取NumPy數(shù)組中唯一值的索引(數(shù)組中唯一值的第一個(gè)索引位置的數(shù)組),只需在np.unique()中傳遞return_index參數(shù):
>>> unique_values, indices_list = np.unique(a, return_index=True)
>>> print(indices_list)
[ 0 2 3 4 5 6 7 12 13 14]
可以將np.unique()中的return_counts參數(shù)與數(shù)組一起傳遞,以獲取NumPy數(shù)組中唯一值的頻率計(jì)數(shù)。
>>> unique_values, occurrence_count = np.unique(a, return_counts=True)
>>> print(occurrence_count)
[3 2 2 2 1 1 1 1 1 1]
這也適用于二維數(shù)組!如果從這個(gè)數(shù)組開始:
>>> a_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [1, 2, 3, 4]])
可以通過以下方式找到唯一的值:
>>> unique_values = np.unique(a_2d)
>>> print(unique_values)
[ 1 2 3 4 5 6 7 8 9 10 11 12]
如果未傳遞axis參數(shù),則二維數(shù)組將被展平。
如果要獲取唯一的行或列,請(qǐng)確保傳遞axis參數(shù)。若要查找唯一的行,請(qǐng)指定axis=0,對(duì)于列,請(qǐng)指定axis=1
>>> unique_rows = np.unique(a_2d, axis=0)
>>> print(unique_rows)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
要獲取唯一行、索引位置和出現(xiàn)次數(shù),可以使用:
>>> unique_rows, indices, occurrence_count = np.unique(
... a_2d, axis=0, return_counts=True, return_index=True)
>>> print(unique_rows)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
>>> print(indices)
[0 1 2]
>>> print(occurrence_count)
[2 1 1]
2 重塑和展平多維數(shù)組
有兩種常用的展平數(shù)組的方法:.flatten() 和.ravel()。
兩者之間的主要區(qū)別在于,使用ravel()創(chuàng)建的新數(shù)組實(shí)際上是對(duì)父數(shù)組的引用(即“視圖”)。這意味著對(duì)新數(shù)組的任何更改也將影響父數(shù)組。因?yàn)閞avel不創(chuàng)建拷貝,所以它的內(nèi)存效率很高。
如果從這個(gè)數(shù)組開始:
>>> x = np.array([[1 , 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
可以使用“flatten”將數(shù)組展平為1D陣列
>>> x.flatten()
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
使用“flatten”時(shí),對(duì)新數(shù)組的更改不會(huì)更改父數(shù)組。
>>> a1 = x.flatten()
>>> a1[0] = 99
>>> print(x) # Original array
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
>>> print(a1) # New array
[99 2 3 4 5 6 7 8 9 10 11 12]
但是使用ravel時(shí),對(duì)新數(shù)組所做的更改將影響父數(shù)組。例如:
>>> a2 = x.ravel()
>>> a2[0] = 98
>>> print(x) # Original array
[[98 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
>>> print(a2) # New array
[98 2 3 4 5 6 7 8 9 10 11 12]
