Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Viết chương trình Python in mảng chỉ số số với giá trị riêng biệt đã sắp xếp trong Series cho trước


Giả sử bạn có một Series và mảng chỉ số số với giá trị riêng biệt đã sắp xếp như sau:

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

Để giải quyết bài toán này, chúng ta sẽ làm theo các bước dưới đây:

Giải pháp

  • Áp dụng pd.factorize() trên danh sách các phần tử không duy nhất và lưu vào index, index_value
index, unique_value = pd.factorize(['mango', 'orange', 'apple', 'orange', 'mango', 'kiwi', 'pomegranate'])
  • In index và các phần tử. Kết quả hiển thị chưa sắp xếp giá trị riêng biệt và index của chúng
  • Áp dụng pd.factorize() trên các phần tử list và đặt sort=True, lưu vào sorted_index, unique_value
sorted_index, unique_value = pd.factorize(['mango', 'orange', 'apple', 'orange', 'mango', 'kiwi', 'pomegranate'], sort=True)
  • Cuối cùng in mảng chỉ số số và các giá trị riêng biệt

Ví dụ

Hãy xem mã dưới đây để hiểu rõ hơn:

import pandas as pd
index, unique_value = pd.factorize(['mango', 'orange', 'apple', 'orange', 'mango', 'kiwi', 'pomegranate'])
print("Without sorting of distinct values - numeric array index")
print(index)
print(unique_value)
print("Sorted distinct 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)

Đầu ra

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