編寫一個 Python 程式,用於列印給定序列中排序後的唯一值的數字索引陣列。


假設,您有一個序列,並且數字索引與排序後的唯一值如下所示:

Sorted distict values - numeric array index
[2 3 0 3 2 1 4]
['apple' 'kiwi' 'mango' 'orange' 'pomegranate']

為了解決這個問題,我們將遵循以下步驟:

解決方案

  • 在非唯一元素列表中應用 pd.factorize() 函式,並將其儲存為 index、index_value。

index,unique_value =
pd.factorize(['mango','orange','apple','orange','mango','kiwi','pomegranate'])
  • 列印索引和元素。結果顯示為未排序的唯一值及其索引。

  • 在列表元素中應用 pd.factorize() 並設定 sort=True,然後將其儲存為 sorted_index、unique_value。

sorted_index,unique_value =
pd.factorize(['mango','orange','apple','orange','mango','kiwi','pomegranate'],sort=True)
  • 最後列印數字索引和唯一值。

示例

讓我們看看下面的程式碼以獲得更好的理解:

import pandas as pd
index,unique_value =
pd.factorize(['mango','orange','apple','orange','mango','kiwi','pomegranate'])
print("Without sorting of distict values-numeric array index")
print(index)
print(unique_value)
print("Sorted distict values - numeric array index")
sorted_index,unique_value =
pd.factorize(['mango','orange','apple','orange','mango','kiwi','pomegranate'],sort=True)
print(sorted_index)
print(unique_value)

輸出

Without sorting of distict values-numeric array index
[0 1 2 1 0 3 4]
['mango' 'orange' 'apple' 'kiwi' 'pomegranate']
Sorted distict values - numeric array index
[2 3 0 3 2 1 4]
['apple' 'kiwi' 'mango' 'orange' 'pomegranate']

更新於: 2021年2月25日

92 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告