Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียนโปรแกรมใน Python เพื่อพิมพ์ดัชนีตัวเลขอาร์เรย์พร้อมค่าที่แตกต่างกันและเรียงลำดับใน Series ที่กำหนด


สมมติว่าคุณมี Series และดัชนีตัวเลขพร้อมค่าที่แตกต่างกันและเรียงลำดับแล้วมีดังนี้:

Sorted distinct 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 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)

ผลลัพธ์

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']