Numpy 的 lexsort(~)
方法返回與列數據對應的多個輸入數組的排序整數索引。請參閱下麵的示例以進行說明。
參數
1.keys
| array_like
共 sequences
您想要排序的鍵。
2. axis
| int
| optional
對輸入數組進行排序的軸。對於二維數組,允許的值如下:
值 |
意義 |
---|---|
|
展平數組並對其進行排序 |
|
按列排序 |
|
按行排序 |
默認情況下,axis=-1
表示僅在最後一個軸上進行排序。對於二維數組,這意味著默認排序行為是按行排序。
返回值
一個 Numpy 數組,保存已排序列的整數索引。
例子
假設我們有以下關於 3 個人的數據:
名 |
姓 |
---|---|
Bob |
Marley |
Alex |
Davis |
Cathy |
Watson |
在代碼中,這將轉換為以下內容:
first_names = np.array(["Bob", "Alex", "Cathy"])
last_names = np.array(["Marley", "Davis", "Watson"])
這裏重要的是我們的數據按列分割 - 我們沒有一個數組來容納所有數據。
按單列排序
要按單列排序,請說出名字:
first_names = np.array(["Bob", "Alex", "Cathy"])
last_names = np.array(["Marley", "Davis", "Watson"])
sorted_indices = np.lexsort([first_names])
sorted_indices
array([1, 0, 2])
這裏返回的是排序數據的索引列表 - ["Alex Davis", "Bob Marley", "Cathy Watson"]
的原始索引分別為 1、0 和 2。
查看排序後的數據:
for i in sorted_indices:
print(first_names[i] + " " + last_names[i])
Alex Davis
Bob Marley
Cathy Watson
按多列排序
要按多列排序:
first_names = np.array(["Bob", "Alex", "Alex"])
last_names = np.array(["Marley", "Davis", "Beck"])
sorted_indices = np.lexsort([first_names, last_names])
sorted_indices
array([2, 1, 0])
在這裏,我們的第一個鍵(即 first_names)有重複的值,因此對於這些值,它們按姓氏排序 - 這就是 Alex Beck 排在 Alex Davis 之前的原因。
查看排序後的數據:
for i in sorted_indices:
print(first_names[i] + " " + last_names[i])
Alex Beck
Alex Davis
Bob Marley
相關用法
- Python len方法用法及代碼示例
- Python len()用法及代碼示例
- Python NumPy less_equal方法用法及代碼示例
- Python numpy string less_equal()用法及代碼示例
- Python calendar leapdays()用法及代碼示例
- Python NumPy less方法用法及代碼示例
- Python list remove()用法及代碼示例
- Python locals()用法及代碼示例
- Python Django logout用法及代碼示例
- Python NumPy logaddexp2方法用法及代碼示例
- Python PIL logical_and() and logical_or()用法及代碼示例
- Python NumPy log方法用法及代碼示例
- Python NumPy logspace方法用法及代碼示例
- Python Django login用法及代碼示例
- Python NumPy logical_or方法用法及代碼示例
- Python NumPy log2方法用法及代碼示例
- Python logging.handlers.SocketHandler.makePickle用法及代碼示例
- Python NumPy lcm方法用法及代碼示例
- Python ldexp()用法及代碼示例
- Python NumPy loadtxt方法用法及代碼示例
- Python PIL logical_xor() and invert()用法及代碼示例
- Python logging.Logger.debug用法及代碼示例
- Python list轉string用法及代碼示例
- Python logging.debug用法及代碼示例
- Python NumPy log1p方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 NumPy | lexsort method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。