ในการจัดเรียงค่าดัชนีและส่งคืนดัชนีที่จะจัดเรียงดัชนี ให้ใช้ index.sort_values() . ตัวสร้างดัชนีผลตอบแทน ตั้งค่าพารามิเตอร์เป็น จริง .
ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import pandas as pd
การสร้างดัชนีนุ่น -
index = pd.Index([50, 10, 70, 95, 110, 90, 30])
แสดงดัชนีหมีแพนด้า −
print("Pandas Index...\n",index) จัดเรียงค่าดัชนี ตามค่าเริ่มต้น เรียงลำดับจากน้อยไปมาก ส่งคืนดัชนีเพื่อจัดเรียงดัชนีโดยใช้พารามิเตอร์ "return_indexer" ด้วยค่า True -
print("\nSort and also return the indices that would sort the index...\n",index.sort_values(return_indexer=True)) ตัวอย่าง
ต่อไปนี้เป็นรหัส -
import pandas as pd
# Creating Pandas index
index = pd.Index([50, 10, 70, 95, 110, 90, 30])
# Display the Pandas index
print("Pandas Index...\n",index)
# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)
# Sort index values
# By default, sorts in Ascending order
# Return the indices to sort the index using the "return_indexer" parameter with value True
print("\nSort and also return the indices that would sort the index...\n",index.sort_values(return_indexer=True)) ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
Pandas Index... Int64Index([50, 10, 70, 95, 110, 90, 30], dtype='int64') Number of elements in the index... 7 Sort and also return the indices that would sort the index... (Int64Index([10, 30, 50, 70, 90, 95, 110], dtype='int64'), array([1, 6, 0, 2, 5, 3, 4], dtype=int64))