日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯(lián)網營銷解決方案
送你一個Python數(shù)據排序的好方法

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

在本教程中,您將學習如何使用.sort_values()和.sort_index(),這將使您能夠有效地對 DataFrame 中的數(shù)據進行排序。

在本教程結束時,您將知道如何:

  • 按一列或多列的值對Pandas DataFrame進行排序
  • 使用ascending參數(shù)更改排序順序
  • 通過index使用對 DataFrame 進行排序.sort_index()
  • 在對值進行排序時組織缺失的數(shù)據
  • 使用set to 對DataFrame進行就地排序inplaceTrue

要學習本教程,您需要對Pandas DataFrames有基本的了解,并對從文件中讀取數(shù)據有一定的了解。

Pandas 排序方法入門

快速提醒一下, DataFrame 是一種數(shù)據結構,行和列都帶有標記的軸。您可以按行或列值以及行或列索引對 DataFrame 進行排序。

行和列都有索引,它是數(shù)據在 DataFrame 中位置的數(shù)字表示。您可以使用 DataFrame 的索引位置從特定行或列中檢索數(shù)據。默認情況下,索引號從零開始。您也可以手動分配自己的索引。

準備數(shù)據集

在本教程中,您將使用美國環(huán)境保護署 (EPA) 為 1984 年至 2021 年間制造的車輛編制的燃油經濟性數(shù)據。EPA 燃油經濟性數(shù)據集非常棒,因為它包含許多不同類型的信息,您可以對其進行排序上,從文本到數(shù)字數(shù)據類型。該數(shù)據集總共包含八十三列。

要繼續(xù),您需要安裝pandas Python 庫。本教程中的代碼是使用 pandas 1.2.0 和Python 3.9.1 執(zhí)行的。

注意:整個燃油經濟性數(shù)據集約為 18 MB。將整個數(shù)據集讀入內存可能需要一兩分鐘。限制行數(shù)和列數(shù)有助于提高性能,但下載數(shù)據仍需要幾秒鐘的時間。

出于分析目的,您將按品牌、型號、年份和其他車輛屬性查看車輛的 MPG(每加侖英里數(shù))數(shù)據。您可以指定要讀入 DataFrame 的列。對于本教程,您只需要可用列的子集。

以下是將燃油經濟性數(shù)據集的相關列讀入 DataFrame 并顯示前五行的命令:

 
 
 
 
  1. >>>
  2. >>> import pandas as pd
  3. >>> column_subset = [
  4. ...     "id",
  5. ...     "make",
  6. ...     "model",
  7. ...     "year",
  8. ...     "cylinders",
  9. ...     "fuelType",
  10. ...     "trany",
  11. ...     "mpgData",
  12. ...     "city08",
  13. ...     "highway08"
  14. ... ]
  15. >>> df = pd.read_csv(
  16. ...     "https://www.fueleconomy.gov/feg/epadata/vehicles.csv",
  17. ...     usecols=column_subset,
  18. ...     nrows=100
  19. ... )
  20. >>> df.head()
  21.    city08  cylinders fuelType  ...  mpgData            trany  year
  22. 0      19          4  Regular  ...        Y     Manual 5-spd  1985
  23. 1       9         12  Regular  ...        N     Manual 5-spd  1985
  24. 2      23          4  Regular  ...        Y     Manual 5-spd  1985
  25. 3      10          8  Regular  ...        N  Automatic 3-spd  1985
  26. 4      17          4  Premium  ...        N     Manual 5-spd  1993
  27. [5 rows x 10 columns]

通過.read_csv()使用數(shù)據集 URL 進行調用,您可以將數(shù)據加載到 DataFrame 中??s小列會導致更快的加載時間和更少的內存使用。為了進一步限制內存消耗并快速了解數(shù)據,您可以使用 指定要加載的行數(shù)nrows。

熟悉 .sort_values()

您用于.sort_values()沿任一軸(列或行)對 D??ataFrame 中的值進行排序。通常,您希望通過一列或多列的值對 DataFrame 中的行進行排序:

上圖顯示了使用.sort_values()根據highway08列中的值對 DataFrame 的行進行排序的結果。這類似于使用列對電子表格中的數(shù)據進行排序的方式。

熟悉 .sort_index()

您用于.sort_index()按行索引或列標簽對 DataFrame 進行排序。與 using 的不同之處.sort_values()在于您是根據其行索引或列名稱對 DataFrame 進行排序,而不是根據這些行或列中的值:

DataFrame 的行索引在上圖中以藍色標出。索引不被視為一列,您通常只有一個行索引。行索引可以被認為是從零開始的行號。

在單列上對 DataFrame 進行排序

要根據單列中的值對 DataFrame 進行排序,您將使用.sort_values(). 默認情況下,這將返回一個按升序排序的新 DataFrame。它不會修改原始 DataFrame。

按升序按列排序

要使用.sort_values(),請將單個參數(shù)傳遞給包含要作為排序依據的列的名稱的方法。在此示例中,您按city08列對 DataFrame 進行排序,該列表示純燃料汽車的城市 MPG:

 
 
 
 
  1. >>>
  2. >>> df.sort_values("city08")
  3.     city08  cylinders fuelType  ...  mpgData            trany  year
  4. 99       9          8  Premium  ...        N  Automatic 4-spd  1993
  5. 1        9         12  Regular  ...        N     Manual 5-spd  1985
  6. 80       9          8  Regular  ...        N  Automatic 3-spd  1985
  7. 47       9          8  Regular  ...        N  Automatic 3-spd  1985
  8. 3       10          8  Regular  ...        N  Automatic 3-spd  1985
  9. ..     ...        ...      ...  ...      ...              ...   ...
  10. 9       23          4  Regular  ...        Y  Automatic 4-spd  1993
  11. 8       23          4  Regular  ...        Y     Manual 5-spd  1993
  12. 7       23          4  Regular  ...        Y  Automatic 3-spd  1993
  13. 76      23          4  Regular  ...        Y     Manual 5-spd  1993
  14. 2       23          4  Regular  ...        Y     Manual 5-spd  1985
  15. [100 rows x 10 columns]

這將使用 中的列值對您的 DataFrame 進行排序city08,首先顯示 MPG 最低的車輛。默認情況下, 按升序 .sort_values()對數(shù)據 進行排序 。盡管您沒有為傳遞給 的參數(shù)指定名稱,但.sort_values()您實際上使用了by參數(shù),您將在下一個示例中看到該參數(shù)。

更改排序順序

的另一個參數(shù).sort_values()是ascending。默認情況下.sort_values()已經ascending設置True。如果您希望 DataFrame 按降序排序 ,則可以傳遞False給此參數(shù):

 
 
 
 
  1. >>>
  2. >>> df.sort_values(
  3. ...     by="city08",
  4. ...     ascending=False
  5. ... )
  6.     city08  cylinders fuelType  ...  mpgData            trany  year
  7. 9       23          4  Regular  ...        Y  Automatic 4-spd  1993
  8. 2       23          4  Regular  ...        Y     Manual 5-spd  1985
  9. 7       23          4  Regular  ...        Y  Automatic 3-spd  1993
  10. 8       23          4  Regular  ...        Y     Manual 5-spd  1993
  11. 76      23          4  Regular  ...        Y     Manual 5-spd  1993
  12. ..     ...        ...      ...  ...      ...              ...   ...
  13. 58      10          8  Regular  ...        N  Automatic 3-spd  1985
  14. 80       9          8  Regular  ...        N  Automatic 3-spd  1985
  15. 1        9         12  Regular  ...        N     Manual 5-spd  1985
  16. 47       9          8  Regular  ...        N  Automatic 3-spd  1985
  17. 99       9          8  Premium  ...        N  Automatic 4-spd  1993
  18. [100 rows x 10 columns]

通過傳遞False到ascending,您可以顛倒排序順序?,F(xiàn)在,您的 DataFrame 按城市條件下測量的平均 MPG 降序排序。MPG 值最高的車輛在第一排。

選擇排序算法

值得注意的是,pandas 允許您選擇不同的排序算法來與.sort_values()和一起使用.sort_index()??捎玫乃惴╭uicksort,mergesort和heapsort。有關這些不同排序算法的更多信息,請查看Python 中的排序算法。

對單列進行排序時默認使用的算法是quicksort。要將其更改為穩(wěn)定的排序算法,請使用mergesort。您可以使用or 中的kind參數(shù)來執(zhí)行此操作,如下所示:.sort_values().sort_index()

 
 
 
 
  1. >>>
  2. >>> df.sort_values(
  3. ...     by="city08",
  4. ...     ascending=False,
  5. ...     kind="mergesort"
  6. ... )
  7.     city08  cylinders fuelType  ...  mpgData            trany  year
  8. 2       23          4  Regular  ...        Y     Manual 5-spd  1985
  9. 7       23          4  Regular  ...        Y  Automatic 3-spd  1993
  10. 8       23          4  Regular  ...        Y     Manual 5-spd  1993
  11. 9       23          4  Regular  ...        Y  Automatic 4-spd  1993
  12. 10      23          4  Regular  ...        Y     Manual 5-spd  1993
  13. ..     ...        ...      ...  ...      ...              ...   ...
  14. 69      10          8  Regular  ...        N  Automatic 3-spd  1985
  15. 1        9         12  Regular  ...        N     Manual 5-spd  1985
  16. 47       9          8  Regular  ...        N  Automatic 3-spd  1985
  17. 80       9          8  Regular  ...        N  Automatic 3-spd  1985
  18. 99       9          8  Premium  ...        N  Automatic 4-spd  1993
  19. [100 rows x 10 columns]

使用kind,您將排序算法設置為mergesort。之前的輸出使用了默認quicksort算法。查看突出顯示的索引,您可以看到行的順序不同。這是因為quicksort不是穩(wěn)定的排序算法,而是mergesort。

注意:在 Pandas 中,kind當您對多個列或標簽進行排序時會被忽略。

當您對具有相同鍵的多條記錄進行排序時,穩(wěn)定的排序算法將在排序后保持這些記錄的原始順序。因此,如果您計劃執(zhí)行多種排序,則必須使用穩(wěn)定的排序算法。

在多列上對 DataFrame 進行排序

在數(shù)據分析中,通常希望根據多列的值對數(shù)據進行排序。想象一下,您有一個包含人們名字和姓氏的數(shù)據集。先按姓然后按名字排序是有意義的,這樣姓氏相同的人會根據他們的名字按字母順序排列。

在第一個示例中,您在名為 的單個列上對 DataFrame 進行了排序city08。從分析的角度來看,城市條件下的 MPG 是決定汽車受歡迎程度的重要因素。除了城市條件下的 MPG,您可能還想查看高速公路條件下的 MPG。要按兩個鍵排序,您可以將列名列表傳遞給by:

 
 
 
 
  1. >>>
  2. >>> df.sort_values(
  3. ...     by=["city08", "highway08"]
  4. ... )[["city08", "highway08"]]
  5.     city08  highway08
  6. 80       9         10
  7. 47       9         11
  8. 99       9         13
  9. 1        9         14
  10. 58      10         11
  11. ..     ...        ...
  12. 9       23         30
  13. 10      23         30
  14. 8       23         31
  15. 76      23         31
  16. 2       23         33
  17. [100 rows x 2 columns]

通過指定列名稱city08和的列表highway08,您可以使用 對兩列上的 DataFrame 進行排序.sort_values()。下一個示例將解釋如何指定排序順序以及為什么注意您使用的列名列表很重要。

按升序按多列排序

要在多個列上對 DataFrame 進行排序,您必須提供一個列名稱列表。例如,要按make和排序model,您應該創(chuàng)建以下列表,然后將其傳遞給.sort_values():

 
 
 
 
  1. >>>
  2. >>> df.sort_values(
  3. ...     by=["make", "model"]
  4. ... )[["make", "model"]]
  5.           make               model
  6. 0   Alfa Romeo  Spider Veloce 2000
  7. 18        Audi                 100
  8. 19        Audi                 100
  9. 20         BMW                740i
  10. 21         BMW               740il
  11. ..         ...                 ...
  12. 12  Volkswagen      Golf III / GTI
  13. 13  Volkswagen           Jetta III
  14. 15  Volkswagen           Jetta III
  15. 16       Volvo                 240
  16. 17       Volvo                 240
  17. [100 rows x 2 columns]

現(xiàn)在您的 DataFrame 按升序排序make。如果有兩個或更多相同的品牌,則按 排序model。在列表中指定列名的順序對應于 DataFrame 的排序方式。

更改列排序順序

由于您使用多列進行排序,因此您可以指定列的排序順序。如果要更改上一個示例中的邏輯排序順序,則可以更改傳遞給by參數(shù)的列表中列名的順序:

 
 
 
 
  1. >>>
  2. >>> df.sort_values(
  3. ...     by=["model", "make"]
  4. ... )[["make", "model"]]
  5.              make        model
  6. 18           Audi          100
  7. 19           Audi          100
  8. 16          Volvo          240
  9. 17          Volvo          240
  10. 75          Mazda          626
  11. ..            ...          ...
  12. 62           Ford  Thunderbird
  13. 63           Ford  Thunderbird
  14. 88     Oldsmobile     Toronado
  15. 42  CX Automotive        XM v6
  16. 43  CX Automotive       XM v6a
  17. [100 rows x 2 columns]

您的 DataFrame 現(xiàn)在按model升序按列排序,然后按make是否有兩個或更多相同模型進行排序。您可以看到更改列的順序也會更改值的排序順序。

按降序按多列排序

到目前為止,您僅對多列按升序排序。在下一個示例中,您將根據make和model列按降序排序。要按降序排序,請設置ascending為False:

 
 
 
 
  1. >>>
  2. >>> df.sort_values(
  3. ...     by=["make", "model"],
  4. ...     ascending=False
  5. ... )[["make", "model"]]
  6.           make               model
  7. 16       Volvo                 240
  8. 17       Volvo                 240
  9. 13  Volkswagen           Jetta III
  10. 15  Volkswagen           Jetta III
  11. 11  Volkswagen      Golf III / GTI
  12. ..         ...                 ...
  13. 21         BMW               740il
  14. 20         BMW                740i
  15. 18        Audi                 100
  16. 19        Audi                 100
  17. 0   Alfa Romeo  Spider Veloce 2000
  18. [100 rows x 2 columns]

該make列中的值按字母順序model倒序排列,對于具有相同make. 對于文本數(shù)據,排序區(qū)分大小寫,這意味著大寫文本將首先按升序出現(xiàn),最后按降序出現(xiàn)。

按具有不同排序順序的多列排序

您可能想知道是否可以使用多個列進行排序并讓這些列使用不同的ascending參數(shù)。使用熊貓,您可以通過單個方法調用來完成此操作。如果要按升序對某些列進行排序,并按降序對某些列進行排序,則可以將布爾值列表傳遞給ascending.

在這個例子中,您排列數(shù)據幀由make,model和city08列,與前兩列按照升序排序和city08按降序排列。為此,您將列名列表傳遞給by和布爾值列表傳遞給ascending:

 
 
 
 
  1. >>>
  2. >>> df.sort_values(
  3. ...     by=["make", "model", "city08"],
  4. ...     ascending=[True, True, False]
  5. ... )[["make", "model", "city08"]]
  6.           make               model  city08
  7. 0   Alfa Romeo  Spider Veloce 2000      19
  8. 18        Audi                 100      17
  9. 19        Audi                 100      17
  10. 20         BMW                740i      14
  11. 21         BMW               740il      14
  12. ..         ...                 ...     ...
  13. 11  Volkswagen      Golf III / GTI      18
  14. 15  Volkswagen           Jetta III      20
  15. 13  Volkswagen           Jetta III      18
  16. 17       Volvo                 240      19
  17. 16       Volvo                 240      18
  18. [100 rows x 3 columns]

現(xiàn)在你的數(shù)據幀進行排序make,并model在按升序排列,但與city08按降序排列列。這很有用,因為它按分類順序對汽車進行分組,并首先顯示最高 MPG 的汽車。

根據索引對 DataFrame 進行排序

在對索引進行排序之前,最好先了解索引代表什么。DataFrame 有一個 .index 屬性,默認情況下它是其行位置的數(shù)字表示。您可以將索引視為行號。它有助于快速行查找和識別。

按升序按索引排序

您可以根據行索引對 DataFrame 進行排序.sort_index()。像在前面的示例中一樣按列值排序會重新排序 DataFrame 中的行,因此索引變得雜亂無章。當您過濾 DataFrame 或刪除或添加行時,也會發(fā)生這種情況。

為了說明 的使用.sort_index(),首先使用以下方法創(chuàng)建一個新的排序 DataFrame .sort_values():

 
 
 
 
  1. >>>
  2. >>> sorted_df = df.sort_values(by=["make", "model"])
  3. >>> sorted_df
  4.     city08  cylinders fuelType  ...  mpgData            trany  year
  5. 0       19          4  Regular  ...        Y     Manual 5-spd  1985
  6. 18      17          6  Premium  ...        Y  Automatic 4-spd  1993
  7. 19      17          6  Premium  ...        N     Manual 5-spd  1993
  8. 20      14          8  Premium  ...        N  Automatic 5-spd  1993
  9. 21      14          8  Premium  ...        N  Automatic 5-spd  1993
  10. ..     ...        ...      ...  ...      ...              ...   ...
  11. 12      21          4  Regular  ...        Y     Manual 5-spd  1993
  12. 13      18          4  Regular  ...        N  Automatic 4-spd  1993
  13. 15      20          4  Regular  ...        N     Manual 5-spd  1993
  14. 16      18          4  Regular  ...        Y  Automatic 4-spd  1993
  15. 17      19          4  Regular  ...        Y     Manual 5-spd  1993
  16. [100 rows x 10 columns]

您已經創(chuàng)建了一個使用多個值排序的 DataFrame。請注意行索引是如何沒有特定順序的。要將新 DataFrame 恢復到原始順序,您可以使用.sort_index():

 
 
 
 
  1. >>>
  2. >>> sorted_df.sort_index()
  3.     city08  cylinders fuelType  ...  mpgData            trany  year
  4. 0       19          4  Regular  ...        Y     Manual 5-spd  1985
  5. 1        9         12  Regular  ...        N     Manual 5-spd  1985
  6. 2       23          4  Regular  ...        Y     Manual 5-spd  1985
  7. 3       10          8  Regular  ...        N  Automatic 3-spd  1985
  8. 4       17          4  Premium  ...        N     Manual 5-spd  1993
  9. ..     ...        ...      ...  ...      ...              ...   ...
  10. 95      17          6  Regular  ...        Y  Automatic 3-spd  1993
  11. 96      17          6  Regular  ...        N  Automatic 4-spd  1993
  12. 97      15          6  Regular  ...        N  Automatic 4-spd  1993
  13. 98      15          6  Regular  ...        N     Manual 5-spd  1993
  14. 99       9          8  Premium  ...        N  Automatic 4-spd  1993
  15. [100 rows x 10 columns]

現(xiàn)在索引按升序排列。就像in.sort_values()的默認參數(shù)是,您可以通過傳遞 更改為降序。對索引進行排序對數(shù)據本身沒有影響,因為值不變。ascending.sort_index()TrueFalse

當您使用. set_index() . 如果要使用make和model列設置自定義索引,則可以將列表傳遞給.set_index():

 
 
 
 
  1. >>>
  2. >>> assigned_index_df = df.set_index(
  3. ...     ["make", "model"]
  4. ... )
  5. >>> assigned_index_df
  6.                                   city08  cylinders  ...            trany  year
  7. make        model                                    ...
  8. Alfa Romeo  Spider Veloce 2000        19          4  ...     Manual 5-spd  1985
  9. Ferrari     Testarossa                 9         12  ...     Manual 5-spd  1985
  10. Dodge       Charger                   23          4  ...     Manual 5-spd  1985
  11.             B150/B250 Wagon 2WD       10          8  ...  Automatic 3-spd  1985
  12. Subaru      Legacy AWD Turbo          17          4  ...     Manual 5-spd  1993
  13.                                   ...        ...  ...              ...   ...
  14. Pontiac     Grand Prix                17          6  ...  Automatic 3-spd  1993
  15.             Grand Prix                17          6  ...  Automatic 4-spd  1993
  16.             Grand Prix                15          6  ...  Automatic 4-spd  1993
  17.             Grand Prix                15          6  ...     Manual 5-spd  1993
  18. Rolls-Royce Brooklands/Brklnds L       9          8  ...  Automatic 4-spd  1993
  19. [100 rows x 8 columns]

使用此方法,您可以用兩個軸標簽替換默認的基于整數(shù)的行索引。這被認為是一個MultiIndex或一個 層次索引 。您的 DataFrame 現(xiàn)在由多個鍵索引,您可以使用.sort_index()以下鍵進行排序:

 
 
 
 
  1. >>>
  2. >>> assigned_index_df.sort_index()
  3.                                city08  cylinders  ...            trany  year
  4. make       model                                  ...
  5. Alfa Romeo Spider Veloce 2000      19          4  ...     Manual 5-spd  1985
  6. Audi       100                     17          6  ...  Automatic 4-spd  1993
  7.            100                     17          6  ...     Manual 5-spd  1993
  8. BMW        740i                    14          8  ...  Automatic 5-spd   網站標題:送你一個Python數(shù)據排序的好方法
    當前鏈接:http://www.5511xx.com/article/ccohpjh.html