Python sort_index(): Order DataFrame Index
In Python, you can specify the order of the index by using the sort_index() method. This method takes an ascending parameter where setting it to True will sort the index in ascending order and setting it to False will sort the index in descending order.
The following is an example code:
import pandas as pd
# 创建一个DataFrame
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data, index=['c', 'a', 'b'])
# 按索引升序排序
df_sorted_ascending = df.sort_index(ascending=True)
print("按索引升序排序:")
print(df_sorted_ascending)
# 按索引降序排序
df_sorted_descending = df.sort_index(ascending=False)
print("\n按索引降序排序:")
print(df_sorted_descending)
Running the above code will sort the DataFrame in ascending and descending order based on the index, respectively.