Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

주어진 시리즈에서 정렬된 고유 값으로 숫자 인덱스 배열을 인쇄하는 프로그램을 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']