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

在本教程中,您將學(xué)習(xí)如何使用.sort_values()和.sort_index(),這將使您能夠有效地對(duì) DataFrame 中的數(shù)據(jù)進(jìn)行排序。
在本教程結(jié)束時(shí),您將知道如何:
- 按一列或多列的值對(duì)Pandas DataFrame進(jìn)行排序
- 使用ascending參數(shù)更改排序順序
- 通過index使用對(duì) DataFrame 進(jìn)行排序.sort_index()
- 在對(duì)值進(jìn)行排序時(shí)組織缺失的數(shù)據(jù)
- 使用set to 對(duì)DataFrame進(jìn)行就地排序inplaceTrue
要學(xué)習(xí)本教程,您需要對(duì)Pandas DataFrames有基本的了解,并對(duì)從文件中讀取數(shù)據(jù)有一定的了解。
Pandas 排序方法入門
快速提醒一下, DataFrame 是一種數(shù)據(jù)結(jié)構(gòu),行和列都帶有標(biāo)記的軸。您可以按行或列值以及行或列索引對(duì) DataFrame 進(jìn)行排序。
行和列都有索引,它是數(shù)據(jù)在 DataFrame 中位置的數(shù)字表示。您可以使用 DataFrame 的索引位置從特定行或列中檢索數(shù)據(jù)。默認(rèn)情況下,索引號(hào)從零開始。您也可以手動(dòng)分配自己的索引。
準(zhǔn)備數(shù)據(jù)集
在本教程中,您將使用美國環(huán)境保護(hù)署 (EPA) 為 1984 年至 2021 年間制造的車輛編制的燃油經(jīng)濟(jì)性數(shù)據(jù)。EPA 燃油經(jīng)濟(jì)性數(shù)據(jù)集非常棒,因?yàn)樗S多不同類型的信息,您可以對(duì)其進(jìn)行排序上,從文本到數(shù)字?jǐn)?shù)據(jù)類型。該數(shù)據(jù)集總共包含八十三列。
要繼續(xù),您需要安裝pandas Python 庫。本教程中的代碼是使用 pandas 1.2.0 和Python 3.9.1 執(zhí)行的。
注意:整個(gè)燃油經(jīng)濟(jì)性數(shù)據(jù)集約為 18 MB。將整個(gè)數(shù)據(jù)集讀入內(nèi)存可能需要一兩分鐘。限制行數(shù)和列數(shù)有助于提高性能,但下載數(shù)據(jù)仍需要幾秒鐘的時(shí)間。
出于分析目的,您將按品牌、型號(hào)、年份和其他車輛屬性查看車輛的 MPG(每加侖英里數(shù))數(shù)據(jù)。您可以指定要讀入 DataFrame 的列。對(duì)于本教程,您只需要可用列的子集。
以下是將燃油經(jīng)濟(jì)性數(shù)據(jù)集的相關(guān)列讀入 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 進(jìn)行調(diào)用,您可以將數(shù)據(jù)加載到 DataFrame 中??s小列會(huì)導(dǎo)致更快的加載時(shí)間和更少的內(nèi)存使用。為了進(jìn)一步限制內(nèi)存消耗并快速了解數(shù)據(jù),您可以使用 指定要加載的行數(shù)nrows。
熟悉 .sort_values()
您用于.sort_values()沿任一軸(列或行)對(duì) D??ataFrame 中的值進(jìn)行排序。通常,您希望通過一列或多列的值對(duì) DataFrame 中的行進(jìn)行排序:
上圖顯示了使用.sort_values()根據(jù)highway08列中的值對(duì) DataFrame 的行進(jìn)行排序的結(jié)果。這類似于使用列對(duì)電子表格中的數(shù)據(jù)進(jìn)行排序的方式。
熟悉 .sort_index()
您用于.sort_index()按行索引或列標(biāo)簽對(duì) DataFrame 進(jìn)行排序。與 using 的不同之處.sort_values()在于您是根據(jù)其行索引或列名稱對(duì) DataFrame 進(jìn)行排序,而不是根據(jù)這些行或列中的值:
DataFrame 的行索引在上圖中以藍(lán)色標(biāo)出。索引不被視為一列,您通常只有一個(gè)行索引。行索引可以被認(rèn)為是從零開始的行號(hào)。
在單列上對(duì) DataFrame 進(jìn)行排序
要根據(jù)單列中的值對(duì) DataFrame 進(jìn)行排序,您將使用.sort_values(). 默認(rèn)情況下,這將返回一個(gè)按升序排序的新 DataFrame。它不會(huì)修改原始 DataFrame。
按升序按列排序
要使用.sort_values(),請(qǐng)將單個(gè)參數(shù)傳遞給包含要作為排序依據(jù)的列的名稱的方法。在此示例中,您按city08列對(duì) DataFrame 進(jìn)行排序,該列表示純?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]
這將使用 中的列值對(duì)您的 DataFrame 進(jìn)行排序city08,首先顯示 MPG 最低的車輛。默認(rèn)情況下, 按升序 .sort_values()對(duì)數(shù)據(jù) 進(jìn)行排序 。盡管您沒有為傳遞給 的參數(shù)指定名稱,但.sort_values()您實(shí)際上使用了by參數(shù),您將在下一個(gè)示例中看到該參數(shù)。
更改排序順序
的另一個(gè)參數(shù).sort_values()是ascending。默認(rèn)情況下.sort_values()已經(jīng)ascending設(shè)置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 按城市條件下測(cè)量的平均 MPG 降序排序。MPG 值最高的車輛在第一排。
選擇排序算法
值得注意的是,pandas 允許您選擇不同的排序算法來與.sort_values()和一起使用.sort_index()??捎玫乃惴╭uicksort,mergesort和heapsort。有關(guān)這些不同排序算法的更多信息,請(qǐng)查看Python 中的排序算法。
對(duì)單列進(jìn)行排序時(shí)默認(rèn)使用的算法是quicksort。要將其更改為穩(wěn)定的排序算法,請(qǐng)使用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,您將排序算法設(shè)置為mergesort。之前的輸出使用了默認(rèn)quicksort算法。查看突出顯示的索引,您可以看到行的順序不同。這是因?yàn)閝uicksort不是穩(wěn)定的排序算法,而是mergesort。
注意:在 Pandas 中,kind當(dāng)您對(duì)多個(gè)列或標(biāo)簽進(jìn)行排序時(shí)會(huì)被忽略。
當(dāng)您對(duì)具有相同鍵的多條記錄進(jìn)行排序時(shí),穩(wěn)定的排序算法將在排序后保持這些記錄的原始順序。因此,如果您計(jì)劃執(zhí)行多種排序,則必須使用穩(wěn)定的排序算法。
在多列上對(duì) DataFrame 進(jìn)行排序
在數(shù)據(jù)分析中,通常希望根據(jù)多列的值對(duì)數(shù)據(jù)進(jìn)行排序。想象一下,您有一個(gè)包含人們名字和姓氏的數(shù)據(jù)集。先按姓然后按名字排序是有意義的,這樣姓氏相同的人會(huì)根據(jù)他們的名字按字母順序排列。
在第一個(gè)示例中,您在名為 的單個(gè)列上對(duì) DataFrame 進(jìn)行了排序city08。從分析的角度來看,城市條件下的 MPG 是決定汽車受歡迎程度的重要因素。除了城市條件下的 MPG,您可能還想查看高速公路條件下的 MPG。要按兩個(gè)鍵排序,您可以將列名列表傳遞給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,您可以使用 對(duì)兩列上的 DataFrame 進(jìn)行排序.sort_values()。下一個(gè)示例將解釋如何指定排序順序以及為什么注意您使用的列名列表很重要。
按升序按多列排序
要在多個(gè)列上對(duì) DataFrame 進(jìn)行排序,您必須提供一個(gè)列名稱列表。例如,要按make和排序model,您應(yīng)該創(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。如果有兩個(gè)或更多相同的品牌,則按 排序model。在列表中指定列名的順序?qū)?yīng)于 DataFrame 的排序方式。
更改列排序順序
由于您使用多列進(jìn)行排序,因此您可以指定列的排序順序。如果要更改上一個(gè)示例中的邏輯排序順序,則可以更改傳遞給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是否有兩個(gè)或更多相同模型進(jìn)行排序。您可以看到更改列的順序也會(huì)更改值的排序順序。
按降序按多列排序
到目前為止,您僅對(duì)多列按升序排序。在下一個(gè)示例中,您將根據(jù)make和model列按降序排序。要按降序排序,請(qǐng)?jiān)O(shè)置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倒序排列,對(duì)于具有相同make. 對(duì)于文本數(shù)據(jù),排序區(qū)分大小寫,這意味著大寫文本將首先按升序出現(xiàn),最后按降序出現(xiàn)。
按具有不同排序順序的多列排序
您可能想知道是否可以使用多個(gè)列進(jìn)行排序并讓這些列使用不同的ascending參數(shù)。使用熊貓,您可以通過單個(gè)方法調(diào)用來完成此操作。如果要按升序?qū)δ承┝羞M(jìn)行排序,并按降序?qū)δ承┝羞M(jìn)行排序,則可以將布爾值列表傳遞給ascending.
在這個(gè)例子中,您排列數(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ù)幀進(jìn)行排序make,并model在按升序排列,但與city08按降序排列列。這很有用,因?yàn)樗捶诸愴樞驅(qū)ζ囘M(jìn)行分組,并首先顯示最高 MPG 的汽車。
根據(jù)索引對(duì) DataFrame 進(jìn)行排序
在對(duì)索引進(jìn)行排序之前,最好先了解索引代表什么。DataFrame 有一個(gè) .index 屬性,默認(rèn)情況下它是其行位置的數(shù)字表示。您可以將索引視為行號(hào)。它有助于快速行查找和識(shí)別。
按升序按索引排序
您可以根據(jù)行索引對(duì) DataFrame 進(jìn)行排序.sort_index()。像在前面的示例中一樣按列值排序會(huì)重新排序 DataFrame 中的行,因此索引變得雜亂無章。當(dāng)您過濾 DataFrame 或刪除或添加行時(shí),也會(huì)發(fā)生這種情況。
為了說明 的使用.sort_index(),首先使用以下方法創(chuàng)建一個(gè)新的排序 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)建了一個(gè)使用多個(gè)值排序的 DataFrame。請(qǐng)注意行索引是如何沒有特定順序的。要將新 DataFrame 恢復(fù)到原始順序,您可以使用.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()的默認(rèn)參數(shù)是,您可以通過傳遞 更改為降序。對(duì)索引進(jìn)行排序?qū)?shù)據(jù)本身沒有影響,因?yàn)橹挡蛔?。ascending.sort_index()TrueFalse
當(dāng)您使用. set_index() . 如果要使用make和model列設(shè)置自定義索引,則可以將列表傳遞給.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]
使用此方法,您可以用兩個(gè)軸標(biāo)簽替換默認(rèn)的基于整數(shù)的行索引。這被認(rèn)為是一個(gè)MultiIndex或一個(gè) 層次索引 。您的 DataFrame 現(xiàn)在由多個(gè)鍵索引,您可以使用.sort_index()以下鍵進(jìn)行排序:
- >>>
- >>> 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 標(biāo)題名稱:送你一個(gè)Python數(shù)據(jù)排序的好方法
新聞來源:http://m.5511xx.com/article/ccohpjh.html


咨詢
建站咨詢
