การเรียงลำดับแพนด้า 101
sortถูกแทนที่ใน v0.20 โดยDataFrame.sort_valuesและDataFrame.sort_index. argsortนอกเหนือจากนี้เรายังมี
ต่อไปนี้เป็นกรณีการใช้งานทั่วไปในการจัดเรียงและวิธีแก้ปัญหาโดยใช้ฟังก์ชันการจัดเรียงใน API ปัจจุบัน ขั้นแรกการตั้งค่า
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})    
df                                                                                                                                        
   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2
จัดเรียงตามคอลัมน์เดียว
ตัวอย่างเช่นหากต้องการจัดเรียงdfตามคอลัมน์ "A" ให้ใช้sort_valuesชื่อคอลัมน์เดียว:
df.sort_values(by='A')
   A  B
0  a  7
3  a  5
4  b  2
1  c  9
2  c  3
หากคุณต้องการความสด RangeIndex DataFrame.reset_indexใช้
จัดเรียงตามหลายคอลัมน์
ตัวอย่างเช่นหากต้องการจัดเรียงตามทั้ง col "A" และ "B" ในdfคุณสามารถส่งรายการไปที่sort_values:
df.sort_values(by=['A', 'B'])
   A  B
3  a  5
0  a  7
4  b  2
2  c  3
1  c  9
เรียงตามดัชนี DataFrame
df2 = df.sample(frac=1)
df2
   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2
คุณสามารถทำได้โดยใช้sort_index:
df2.sort_index()
   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2
df.equals(df2)                                                                                                                            
df.equals(df2.sort_index())                                                                                                               
นี่คือวิธีการเปรียบเทียบกับประสิทธิภาพ:
%timeit df2.sort_index()                                                                                                                  
%timeit df2.iloc[df2.index.argsort()]                                                                                                     
%timeit df2.reindex(np.sort(df2.index))                                                                                                   
605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
เรียงตามรายการดัชนี
ตัวอย่างเช่น,
idx = df2.index.argsort()
idx
ปัญหา "การเรียงลำดับ" นี้เป็นปัญหาในการจัดทำดัชนีอย่างง่าย เพียงแค่ส่งป้ายจำนวนเต็มไปilocก็จะทำ
df.iloc[idx]
   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2