Write a program in Python to print numeric index array with sorted distinct values in a given series

PythonPandasServer Side ProgrammingProgramming

Assume, you have a series and the numberic index with sorted distinct values are −

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

To solve this, we will follow the steps given below −

Solution

  • Apply pd.factorize() function inside list of non-unique elements and save it as index,index_value.

index,unique_value =
pd.factorize(['mango','orange','apple','orange','mango','kiwi','pomegranate'])
  • Print the index and elements. Result is diplayed without sorting of distinct values and its index

  • Apply pd.factorize() inside list elements and set sort=True then save it as sorted_index,unique_value

sorted_index,unique_value =
pd.factorize(['mango','orange','apple','orange','mango','kiwi','pomegranate'],sort=True)
  • Finally print the numeric index and distinct values

Example

Let’s see the below code to get better understanding −

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)

Output

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']
raja
Published on 12-Feb-2021 10:55:40
Advertisements