iT邦幫忙

2025 iThome 鐵人賽

DAY 23
0
佛心分享-讓我升級的那些書

菜雞學習 pandas 的 30 日讀書分享系列 第 23

菜雞學習 pandas 的 30 日讀書分享【Day 23】排序 (上)

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20250820/20168290vmDAMB7ISC.jpg

排序 (上)

使用某個條件來排序資料組是另一個重要的內建操作,若要按照辭典順序來排序或是欄標籤,可以使用 sort_value() 方法,它會回傳一個排序好的新物件:

In [234]: obj = pd.Series(np.arange(4), index=["d", "a", "b", "c"])

In [235]: obj
Out[235]:
d    0
a    1
b    2
c    3
dtype: int64

In [236]: obj.sort_index()
Out[236]:
a    1
b    2
c    3
d    0
dtype: int64

對於 DataFrame,可以使用任何一軸索引來排序:

In [237]: frame = pd.DataFrame(np.arange(8).reshape((2, 4)),
                               index=["three", "one"],
                               columns=["d", "a", "b", "c"])

In [238]: frame
Out[238]:
       d  a  b  c
three  0  1  2  3
one    4  5  6  7

In [239]: frame.sort_index()
Out[239]:
       d  a  b  c
one    4  5  6  7
three  0  1  2  3

In [240]: frame.sort_index(axis="columns")
Out[240]:
       a  b  c  d
three  1  2  3  0
one    5  6  7  4

在預設情況下資料會被升序,但也可以使用降序排序:

In [241]: frame.sort_index(axis="columns", ascending=False)
Out[241]:
       d  c  b  a
one    0  3  2  1
three  4  7  6  5

若使用 Series 的值來排序,可以使用 sort_values() 方法:

In [242]: obj = pd.Series([4, 7, -3, 2])

In [243]: obj.sort_values()
Out[243]:
2  -3
3   2
0   4
1   7
dtype: int64

今日的分享就到這囉,我們明天見,掰掰!


上一篇
菜雞學習 pandas 的 30 日讀書分享【Day 22】DataFrame 與 Series 之間運算
下一篇
菜雞學習 pandas 的 30 日讀書分享【Day 24】排序 (下)
系列文
菜雞學習 pandas 的 30 日讀書分享30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言