使用某個條件來排序資料組是另一個重要的內建操作,若要按照辭典順序來排序或是欄標籤,可以使用 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
今日的分享就到這囉,我們明天見,掰掰!