reindex
是 pandas 物件的重要方法,將一個物件裡的值按照指定的索引重新排序並產生一個新物件。
In [98]: obj = pd.Series([4.5, 7.2, -5.3, 3.6], index=["d", "b", "a", "c"])
In [99]: obj
Out[99]: obj
d 4.5
b 7.2
a -5.3
c 3.6
dtypeL float64
對著 Series 呼叫 reindex
會按照新索引來重新排列資料,如果物件沒有指定的索引值,則會加入 NaN
:
In [100]: obj2 = obj.reindex(["a", "b", "c", "d", "e"])
In [101]: obj2
Out[101]:
a -5.3
b 7.2
c 3.6
d 4.5
e NaN
dtype: float64
如果資料是有序的,例如時間序列,可能想要在做 reindex
的時候做一些填值,可以使用 method
選項與 ffill
等方法來做這件事:
In [102]: obj3 = pd.Series(["blue", "purple", "yellow"], index=[0, 2, 4])
In [103]: obj3
Out[103]:
0 blue
2 purple
4 yellow
dtype: object
In [104]: obj3.reindex(np.arange(6), method="ffill")
Out[104]:
0 blue
1 blue
2 purple
3 purple
4 yellow
5 yellow
dtype: object
對著 DataFrame 使用 reindex
可能會修改索引、欄、列,如果只傳入序列,則會 reindex
橫列:
In [105]: frame = pd.DataFrame(np.arange(9).reshape((3,3)),
index=["a", "c", "d"],
columns=["Ohio", "Texas", "California"])
In [106]: frame
Out[106]:
Ohio Texas California
a 0 1 2
c 3 4 5
d 6 7 8
In [107]: frame2 = frame.reindex(index=["a", "b", "c", "d"])
In [108]: frame2
Out[108]:
Ohio Texas California
a 0.0 1.0 2.0
b NaN NaN NaN
c 3.0 4.0 5.0
d 6.0 7.0 8.0
今日的分享就到這囉,我們明天見,掰掰!