编写一个 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 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.