排序是数据操作和分析中的一个基本操作,它涉及将数据按特定顺序排列。
排序对于诸如组织数据以提高可读性、识别模式、进行比较和促进进一步分析等任务至关重要。
在 Pandas 中排序 DataFrame
在 Pandas 中,我们可以使用 sort_values()
函数来排序 DataFrame。例如,
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [28, 22, 25]}
df = pd.DataFrame(data)
# sort DataFrame by Age in ascending order
sorted_df = df.sort_values(by='Age')
print(sorted_df.to_string(index=False))
输出
Name Age
Bob 22
Charlie 25
Alice 28
在上面的示例中,df.sort_values(by='Age')
根据 Age 列中的值按升序排序 df DataFrame。结果存储在 sorted_df 变量中。
要按降序排序值,我们使用 ascending 参数,如下所示:
sorted_df = df.sort_values(by='Age', ascending=False)
输出将是
Name Age
Alice 28
Charlie 25
Bob 22
注意:.to_string(index=False)
用于显示不带索引的值。
按多列排序 Pandas DataFrame
我们还可以按多列在 Pandas 中排序 DataFrame。当我们按多列排序 Pandas DataFrame 时,排序的优先级取决于所列列的顺序。
要在 Pandas 中按多列排序,您可以将所需的列作为列表传递给 sort_values()
方法中的 by
参数。方法如下。
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 22, 30, 22],
'Score': [85, 90, 75, 80]}
df = pd.DataFrame(data)
# 1. Sort DataFrame by 'Age' and then by 'Score' (Both in ascending order)
df1 = df.sort_values(by=['Age', 'Score'])
print("Sorting by 'Age' (ascending) and then by 'Score' (ascending):\n")
print(df1.to_string(index=False))
print()
# 2. Sort DataFrame by 'Age' in ascending order, and then by 'Score' in descending order
df2 = df.sort_values(by=['Age', 'Score'], ascending=[True, False])
print("Sorting by 'Age' (ascending) and then by 'Score' (descending):\n")
print(df2.to_string(index=False))
输出
Name Age Score
Bob 22 90
David 22 80
Alice 25 85
Charlie 30 75
这里,
- df1 显示了默认排序行为(两列均按升序排列)。
- df2 显示了自定义排序,其中
Age
按升序排列,Score
按降序排列。
排序 Pandas Series
在 Pandas 中,我们可以使用 sort_values()
函数来排序 Series。例如,
import pandas as pd
ages = pd.Series([28, 22, 25], name='Age')
# sort Series in ascending order
sorted_ages = ages.sort_values()
print(sorted_ages.to_string(index=False))
输出
22 25 28
在此,ages.sort_values()
按升序排序 ages Series。排序结果被赋给 sorted_ages 变量。
# 使用 sort_index() 排序 Pandas DataFrame 的索引
我们还可以使用 sort_index()
函数在 Pandas 中按 DataFrame 的索引进行排序。
sort_index()
函数用于按索引排序 DataFrame 或 Series。这对于以逻辑顺序组织数据、提高查询性能和确保一致的数据表示很有用。
让我们看一个例子。
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [28, 22, 25]}
# create a DataFrame with a non-sequential index
df = pd.DataFrame(data, index=[2, 0, 1])
print("Original DataFrame:")
print(df.to_string(index=True))
print("\n")
# sort DataFrame by index in ascending order
sorted_df = df.sort_index()
print("Sorted DataFrame by index:")
print(sorted_df.to_string(index=True))
输出
Original DataFrame:
Name Age
2 Alice 28
0 Bob 22
1 Charlie 25
Sorted DataFrame by index:
Name Age
0 Bob 22
1 Charlie 25
2 Alice 28
在上面的示例中,我们从数据字典创建了一个带有非顺序索引的 df DataFrame。
index
参数指定为 [2, 0, 1]
,这意味着行将不具有默认的顺序索引(0、1、2),而是具有提供的非顺序索引。
然后,我们使用 sort_index()
方法按升序对 df DataFrame 的索引进行排序。