新聞中心
學習 Pandas 排序方法 是開始或練習使用 Python進行基本數(shù)據(jù)分析的好方法。最常見的數(shù)據(jù)分析是使用電子表格、SQL或pandas 完成的。使用 Pandas 的一大優(yōu)點是它可以處理大量數(shù)據(jù)并提供高性能的數(shù)據(jù)操作能力。

在本教程中,您將學習如何使用.sort_values()和.sort_index(),這將使您能夠有效地對 DataFrame 中的數(shù)據(jù)進行排序。
在本教程結束時,您將知道如何:
- 按一列或多列的值對Pandas DataFrame進行排序
- 使用ascending參數(shù)更改排序順序
- 通過index使用對 DataFrame 進行排序.sort_index()
- 在對值進行排序時組織缺失的數(shù)據(jù)
- 使用set to 對DataFrame進行就地排序inplaceTrue
要學習本教程,您需要對Pandas DataFrames有基本的了解,并對從文件中讀取數(shù)據(jù)有一定的了解。
Pandas 排序方法入門
快速提醒一下, DataFrame 是一種數(shù)據(jù)結構,行和列都帶有標記的軸。您可以按行或列值以及行或列索引對 DataFrame 進行排序。
行和列都有索引,它是數(shù)據(jù)在 DataFrame 中位置的數(shù)字表示。您可以使用 DataFrame 的索引位置從特定行或列中檢索數(shù)據(jù)。默認情況下,索引號從零開始。您也可以手動分配自己的索引。
準備數(shù)據(jù)集
在本教程中,您將使用美國環(huán)境保護署 (EPA) 為 1984 年至 2021 年間制造的車輛編制的燃油經(jīng)濟性數(shù)據(jù)。EPA 燃油經(jīng)濟性數(shù)據(jù)集非常棒,因為它包含許多不同類型的信息,您可以對其進行排序上,從文本到數(shù)字數(shù)據(jù)類型。該數(shù)據(jù)集總共包含八十三列。
要繼續(xù),您需要安裝pandas Python 庫。本教程中的代碼是使用 pandas 1.2.0 和Python 3.9.1 執(zhí)行的。
注意:整個燃油經(jīng)濟性數(shù)據(jù)集約為 18 MB。將整個數(shù)據(jù)集讀入內(nèi)存可能需要一兩分鐘。限制行數(shù)和列數(shù)有助于提高性能,但下載數(shù)據(jù)仍需要幾秒鐘的時間。
出于分析目的,您將按品牌、型號、年份和其他車輛屬性查看車輛的 MPG(每加侖英里數(shù))數(shù)據(jù)。您可以指定要讀入 DataFrame 的列。對于本教程,您只需要可用列的子集。
以下是將燃油經(jīng)濟性數(shù)據(jù)集的相關列讀入 DataFrame 并顯示前五行的命令:
- >>>
- >>> import pandas as pd
- >>> column_subset = [
- ... "id",
- ... "make",
- ... "model",
- ... "year",
- ... "cylinders",
- ... "fuelType",
- ... "trany",
- ... "mpgData",
- ... "city08",
- ... "highway08"
- ... ]
- >>> df = pd.read_csv(
- ... "https://www.fueleconomy.gov/feg/epadata/vehicles.csv",
- ... usecols=column_subset,
- ... nrows=100
- ... )
- >>> df.head()
- city08 cylinders fuelType ... mpgData trany year
- 0 19 4 Regular ... Y Manual 5-spd 1985
- 1 9 12 Regular ... N Manual 5-spd 1985
- 2 23 4 Regular ... Y Manual 5-spd 1985
- 3 10 8 Regular ... N Automatic 3-spd 1985
- 4 17 4 Premium ... N Manual 5-spd 1993
- [5 rows x 10 columns]
通過.read_csv()使用數(shù)據(jù)集 URL 進行調用,您可以將數(shù)據(jù)加載到 DataFrame 中??s小列會導致更快的加載時間和更少的內(nèi)存使用。為了進一步限制內(nèi)存消耗并快速了解數(shù)據(jù),您可以使用 指定要加載的行數(shù)nrows。
熟悉 .sort_values()
您用于.sort_values()沿任一軸(列或行)對 D??ataFrame 中的值進行排序。通常,您希望通過一列或多列的值對 DataFrame 中的行進行排序:
上圖顯示了使用.sort_values()根據(jù)highway08列中的值對 DataFrame 的行進行排序的結果。這類似于使用列對電子表格中的數(shù)據(jù)進行排序的方式。
熟悉 .sort_index()
您用于.sort_index()按行索引或列標簽對 DataFrame 進行排序。與 using 的不同之處.sort_values()在于您是根據(jù)其行索引或列名稱對 DataFrame 進行排序,而不是根據(jù)這些行或列中的值:
DataFrame 的行索引在上圖中以藍色標出。索引不被視為一列,您通常只有一個行索引。行索引可以被認為是從零開始的行號。
在單列上對 DataFrame 進行排序
要根據(jù)單列中的值對 DataFrame 進行排序,您將使用.sort_values(). 默認情況下,這將返回一個按升序排序的新 DataFrame。它不會修改原始 DataFrame。
按升序按列排序
要使用.sort_values(),請將單個參數(shù)傳遞給包含要作為排序依據(jù)的列的名稱的方法。在此示例中,您按city08列對 DataFrame 進行排序,該列表示純?nèi)剂掀嚨某鞘?MPG:
- >>>
- >>> df.sort_values("city08")
- city08 cylinders fuelType ... mpgData trany year
- 99 9 8 Premium ... N Automatic 4-spd 1993
- 1 9 12 Regular ... N Manual 5-spd 1985
- 80 9 8 Regular ... N Automatic 3-spd 1985
- 47 9 8 Regular ... N Automatic 3-spd 1985
- 3 10 8 Regular ... N Automatic 3-spd 1985
- .. ... ... ... ... ... ... ...
- 9 23 4 Regular ... Y Automatic 4-spd 1993
- 8 23 4 Regular ... Y Manual 5-spd 1993
- 7 23 4 Regular ... Y Automatic 3-spd 1993
- 76 23 4 Regular ... Y Manual 5-spd 1993
- 2 23 4 Regular ... Y Manual 5-spd 1985
- [100 rows x 10 columns]
這將使用 中的列值對您的 DataFrame 進行排序city08,首先顯示 MPG 最低的車輛。默認情況下, 按升序 .sort_values()對數(shù)據(jù) 進行排序 。盡管您沒有為傳遞給 的參數(shù)指定名稱,但.sort_values()您實際上使用了by參數(shù),您將在下一個示例中看到該參數(shù)。
更改排序順序
的另一個參數(shù).sort_values()是ascending。默認情況下.sort_values()已經(jīng)ascending設置True。如果您希望 DataFrame 按降序排序 ,則可以傳遞False給此參數(shù):
- >>>
- >>> df.sort_values(
- ... by="city08",
- ... ascending=False
- ... )
- city08 cylinders fuelType ... mpgData trany year
- 9 23 4 Regular ... Y Automatic 4-spd 1993
- 2 23 4 Regular ... Y Manual 5-spd 1985
- 7 23 4 Regular ... Y Automatic 3-spd 1993
- 8 23 4 Regular ... Y Manual 5-spd 1993
- 76 23 4 Regular ... Y Manual 5-spd 1993
- .. ... ... ... ... ... ... ...
- 58 10 8 Regular ... N Automatic 3-spd 1985
- 80 9 8 Regular ... N Automatic 3-spd 1985
- 1 9 12 Regular ... N Manual 5-spd 1985
- 47 9 8 Regular ... N Automatic 3-spd 1985
- 99 9 8 Premium ... N Automatic 4-spd 1993
- [100 rows x 10 columns]
通過傳遞False到ascending,您可以顛倒排序順序?,F(xiàn)在,您的 DataFrame 按城市條件下測量的平均 MPG 降序排序。MPG 值最高的車輛在第一排。
選擇排序算法
值得注意的是,pandas 允許您選擇不同的排序算法來與.sort_values()和一起使用.sort_index()。可用的算法quicksort,mergesort和heapsort。有關這些不同排序算法的更多信息,請查看Python 中的排序算法。
對單列進行排序時默認使用的算法是quicksort。要將其更改為穩(wěn)定的排序算法,請使用mergesort。您可以使用or 中的kind參數(shù)來執(zhí)行此操作,如下所示:.sort_values().sort_index()
- >>>
- >>> df.sort_values(
- ... by="city08",
- ... ascending=False,
- ... kind="mergesort"
- ... )
- city08 cylinders fuelType ... mpgData trany year
- 2 23 4 Regular ... Y Manual 5-spd 1985
- 7 23 4 Regular ... Y Automatic 3-spd 1993
- 8 23 4 Regular ... Y Manual 5-spd 1993
- 9 23 4 Regular ... Y Automatic 4-spd 1993
- 10 23 4 Regular ... Y Manual 5-spd 1993
- .. ... ... ... ... ... ... ...
- 69 10 8 Regular ... N Automatic 3-spd 1985
- 1 9 12 Regular ... N Manual 5-spd 1985
- 47 9 8 Regular ... N Automatic 3-spd 1985
- 80 9 8 Regular ... N Automatic 3-spd 1985
- 99 9 8 Premium ... N Automatic 4-spd 1993
- [100 rows x 10 columns]
使用kind,您將排序算法設置為mergesort。之前的輸出使用了默認quicksort算法。查看突出顯示的索引,您可以看到行的順序不同。這是因為quicksort不是穩(wěn)定的排序算法,而是mergesort。
注意:在 Pandas 中,kind當您對多個列或標簽進行排序時會被忽略。
當您對具有相同鍵的多條記錄進行排序時,穩(wěn)定的排序算法將在排序后保持這些記錄的原始順序。因此,如果您計劃執(zhí)行多種排序,則必須使用穩(wěn)定的排序算法。
在多列上對 DataFrame 進行排序
在數(shù)據(jù)分析中,通常希望根據(jù)多列的值對數(shù)據(jù)進行排序。想象一下,您有一個包含人們名字和姓氏的數(shù)據(jù)集。先按姓然后按名字排序是有意義的,這樣姓氏相同的人會根據(jù)他們的名字按字母順序排列。
在第一個示例中,您在名為 的單個列上對 DataFrame 進行了排序city08。從分析的角度來看,城市條件下的 MPG 是決定汽車受歡迎程度的重要因素。除了城市條件下的 MPG,您可能還想查看高速公路條件下的 MPG。要按兩個鍵排序,您可以將列名列表傳遞給by:
- >>>
- >>> df.sort_values(
- ... by=["city08", "highway08"]
- ... )[["city08", "highway08"]]
- city08 highway08
- 80 9 10
- 47 9 11
- 99 9 13
- 1 9 14
- 58 10 11
- .. ... ...
- 9 23 30
- 10 23 30
- 8 23 31
- 76 23 31
- 2 23 33
- [100 rows x 2 columns]
通過指定列名稱city08和的列表highway08,您可以使用 對兩列上的 DataFrame 進行排序.sort_values()。下一個示例將解釋如何指定排序順序以及為什么注意您使用的列名列表很重要。
按升序按多列排序
要在多個列上對 DataFrame 進行排序,您必須提供一個列名稱列表。例如,要按make和排序model,您應該創(chuàng)建以下列表,然后將其傳遞給.sort_values():
- >>>
- >>> df.sort_values(
- ... by=["make", "model"]
- ... )[["make", "model"]]
- make model
- 0 Alfa Romeo Spider Veloce 2000
- 18 Audi 100
- 19 Audi 100
- 20 BMW 740i
- 21 BMW 740il
- .. ... ...
- 12 Volkswagen Golf III / GTI
- 13 Volkswagen Jetta III
- 15 Volkswagen Jetta III
- 16 Volvo 240
- 17 Volvo 240
- [100 rows x 2 columns]
現(xiàn)在您的 DataFrame 按升序排序make。如果有兩個或更多相同的品牌,則按 排序model。在列表中指定列名的順序對應于 DataFrame 的排序方式。
更改列排序順序
由于您使用多列進行排序,因此您可以指定列的排序順序。如果要更改上一個示例中的邏輯排序順序,則可以更改傳遞給by參數(shù)的列表中列名的順序:
- >>>
- >>> df.sort_values(
- ... by=["model", "make"]
- ... )[["make", "model"]]
- make model
- 18 Audi 100
- 19 Audi 100
- 16 Volvo 240
- 17 Volvo 240
- 75 Mazda 626
- .. ... ...
- 62 Ford Thunderbird
- 63 Ford Thunderbird
- 88 Oldsmobile Toronado
- 42 CX Automotive XM v6
- 43 CX Automotive XM v6a
- [100 rows x 2 columns]
您的 DataFrame 現(xiàn)在按model升序按列排序,然后按make是否有兩個或更多相同模型進行排序。您可以看到更改列的順序也會更改值的排序順序。
按降序按多列排序
到目前為止,您僅對多列按升序排序。在下一個示例中,您將根據(jù)make和model列按降序排序。要按降序排序,請設置ascending為False:
- >>>
- >>> df.sort_values(
- ... by=["make", "model"],
- ... ascending=False
- ... )[["make", "model"]]
- make model
- 16 Volvo 240
- 17 Volvo 240
- 13 Volkswagen Jetta III
- 15 Volkswagen Jetta III
- 11 Volkswagen Golf III / GTI
- .. ... ...
- 21 BMW 740il
- 20 BMW 740i
- 18 Audi 100
- 19 Audi 100
- 0 Alfa Romeo Spider Veloce 2000
- [100 rows x 2 columns]
該make列中的值按字母順序model倒序排列,對于具有相同make. 對于文本數(shù)據(jù),排序區(qū)分大小寫,這意味著大寫文本將首先按升序出現(xiàn),最后按降序出現(xiàn)。
按具有不同排序順序的多列排序
您可能想知道是否可以使用多個列進行排序并讓這些列使用不同的ascending參數(shù)。使用熊貓,您可以通過單個方法調用來完成此操作。如果要按升序對某些列進行排序,并按降序對某些列進行排序,則可以將布爾值列表傳遞給ascending.
在這個例子中,您排列數(shù)據(jù)幀由make,model和city08列,與前兩列按照升序排序和city08按降序排列。為此,您將列名列表傳遞給by和布爾值列表傳遞給ascending:
- >>>
- >>> df.sort_values(
- ... by=["make", "model", "city08"],
- ... ascending=[True, True, False]
- ... )[["make", "model", "city08"]]
- make model city08
- 0 Alfa Romeo Spider Veloce 2000 19
- 18 Audi 100 17
- 19 Audi 100 17
- 20 BMW 740i 14
- 21 BMW 740il 14
- .. ... ... ...
- 11 Volkswagen Golf III / GTI 18
- 15 Volkswagen Jetta III 20
- 13 Volkswagen Jetta III 18
- 17 Volvo 240 19
- 16 Volvo 240 18
- [100 rows x 3 columns]
現(xiàn)在你的數(shù)據(jù)幀進行排序make,并model在按升序排列,但與city08按降序排列列。這很有用,因為它按分類順序對汽車進行分組,并首先顯示最高 MPG 的汽車。
根據(jù)索引對 DataFrame 進行排序
在對索引進行排序之前,最好先了解索引代表什么。DataFrame 有一個 .index 屬性,默認情況下它是其行位置的數(shù)字表示。您可以將索引視為行號。它有助于快速行查找和識別。
按升序按索引排序
您可以根據(jù)行索引對 DataFrame 進行排序.sort_index()。像在前面的示例中一樣按列值排序會重新排序 DataFrame 中的行,因此索引變得雜亂無章。當您過濾 DataFrame 或刪除或添加行時,也會發(fā)生這種情況。
為了說明 的使用.sort_index(),首先使用以下方法創(chuàng)建一個新的排序 DataFrame .sort_values():
- >>>
- >>> sorted_df = df.sort_values(by=["make", "model"])
- >>> sorted_df
- city08 cylinders fuelType ... mpgData trany year
- 0 19 4 Regular ... Y Manual 5-spd 1985
- 18 17 6 Premium ... Y Automatic 4-spd 1993
- 19 17 6 Premium ... N Manual 5-spd 1993
- 20 14 8 Premium ... N Automatic 5-spd 1993
- 21 14 8 Premium ... N Automatic 5-spd 1993
- .. ... ... ... ... ... ... ...
- 12 21 4 Regular ... Y Manual 5-spd 1993
- 13 18 4 Regular ... N Automatic 4-spd 1993
- 15 20 4 Regular ... N Manual 5-spd 1993
- 16 18 4 Regular ... Y Automatic 4-spd 1993
- 17 19 4 Regular ... Y Manual 5-spd 1993
- [100 rows x 10 columns]
您已經(jīng)創(chuàng)建了一個使用多個值排序的 DataFrame。請注意行索引是如何沒有特定順序的。要將新 DataFrame 恢復到原始順序,您可以使用.sort_index():
- >>>
- >>> sorted_df.sort_index()
- city08 cylinders fuelType ... mpgData trany year
- 0 19 4 Regular ... Y Manual 5-spd 1985
- 1 9 12 Regular ... N Manual 5-spd 1985
- 2 23 4 Regular ... Y Manual 5-spd 1985
- 3 10 8 Regular ... N Automatic 3-spd 1985
- 4 17 4 Premium ... N Manual 5-spd 1993
- .. ... ... ... ... ... ... ...
- 95 17 6 Regular ... Y Automatic 3-spd 1993
- 96 17 6 Regular ... N Automatic 4-spd 1993
- 97 15 6 Regular ... N Automatic 4-spd 1993
- 98 15 6 Regular ... N Manual 5-spd 1993
- 99 9 8 Premium ... N Automatic 4-spd 1993
- [100 rows x 10 columns]
現(xiàn)在索引按升序排列。就像in.sort_values()的默認參數(shù)是,您可以通過傳遞 更改為降序。對索引進行排序對數(shù)據(jù)本身沒有影響,因為值不變。ascending.sort_index()TrueFalse
當您使用. set_index() . 如果要使用make和model列設置自定義索引,則可以將列表傳遞給.set_index():
- >>>
- >>> assigned_index_df = df.set_index(
- ... ["make", "model"]
- ... )
- >>> assigned_index_df
- city08 cylinders ... trany year
- make model ...
- Alfa Romeo Spider Veloce 2000 19 4 ... Manual 5-spd 1985
- Ferrari Testarossa 9 12 ... Manual 5-spd 1985
- Dodge Charger 23 4 ... Manual 5-spd 1985
- B150/B250 Wagon 2WD 10 8 ... Automatic 3-spd 1985
- Subaru Legacy AWD Turbo 17 4 ... Manual 5-spd 1993
- ... ... ... ... ...
- Pontiac Grand Prix 17 6 ... Automatic 3-spd 1993
- Grand Prix 17 6 ... Automatic 4-spd 1993
- Grand Prix 15 6 ... Automatic 4-spd 1993
- Grand Prix 15 6 ... Manual 5-spd 1993
- Rolls-Royce Brooklands/Brklnds L 9 8 ... Automatic 4-spd 1993
- [100 rows x 8 columns]
使用此方法,您可以用兩個軸標簽替換默認的基于整數(shù)的行索引。這被認為是一個MultiIndex或一個 層次索引 。您的 DataFrame 現(xiàn)在由多個鍵索引,您可以使用.sort_index()以下鍵進行排序:
- >>>
- >>> assigned_index_df.sort_index()
- city08 cylinders ... trany year
- make model ...
- Alfa Romeo Spider Veloce 2000 19 4 ... Manual 5-spd 1985
- Audi 100 17 6 ... Automatic 4-spd 1993
- 100 17 6 ... Manual 5-spd 1993
- BMW 740i 14 8 ... Automatic 5-spd 分享標題:送你一個Python數(shù)據(jù)排序的好方法
分享路徑:http://m.fisionsoft.com.cn/article/ccohpjh.html


咨詢
建站咨詢
