」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何根據字典自定義大熊貓數據框列進行排序?

如何根據字典自定義大熊貓數據框列進行排序?

發佈於2025-03-25
瀏覽:579

How Can I Custom Sort a Pandas DataFrame Column Based on a Dictionary?
在pandas dataframes中自定義排序

您的pandas dataframe帶有包含月份名稱的列。您想使用自定義詞典進行對本列進行分類,例如:

custom_dict = {'3月':0,'April':1,'dec':3} 將月列轉換為類別系列,指定自定義訂購:

)

Sort the dataframe based on the categorical column:
df.sort_values("m")

custom_dict = {'March':0, 'April':1, 'Dec':3}

Using an Intermediary Series:

Prior to Pandas 0.15, you could utilize一個用於實現自定義排序的中間序列:

將自定義字典應用於“月”列: s = df ['m']。 InterMediary系列:

將dataFrame設置為排序的Intermediary系列和sort:
  1. In newer versions of Pandas, Series offers a replace method that allows for a more concise solution:

    df['m'].replace({'March':0, 'April':1, 'Dec':3})
    custom_dict = {'March':0, 'April':1, 'Dec':3}
    This method replaces the month values with the corresponding sorting values specified in the dictionary.基於修改月份列對數據框進行排序將獲得所需的自定義訂單。
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3