pandas對(duì)象的一個(gè)重要方法是reindex,其作用是創(chuàng)建一個(gè)新對(duì)象,它的數(shù)據(jù)符合新的索引??聪旅娴睦樱?/p>
In [91]: obj = pd.Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c'])
In [92]: obj
Out[92]:
d 4.5
b 7.2
a -5.3
c 3.6
dtype: float64
用該Series的reindex將會(huì)根據(jù)新索引進(jìn)行重排。如果某個(gè)索引值當(dāng)前不存在,就引入缺失值:
In [93]: obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'])
In [94]: obj2
Out[94]:
a -5.3
b 7.2
c 3.6
d 4.5
e NaN
dtype: float64
對(duì)于時(shí)間序列這樣的有序數(shù)據(jù),重新索引時(shí)可能需要做一些插值處理。插值處理就是根據(jù)現(xiàn)有的離散數(shù)據(jù),填充缺失的值使其變成連續(xù)的數(shù)據(jù)。method選項(xiàng)即可達(dá)到此目的,例如,使用ffill可以實(shí)現(xiàn)前向值填充:
In [95]: obj3 = pd.Series(['blue', 'purple', 'yellow'], index=[0, 2, 4])
In [96]: obj3
Out[96]:
0 blue
2 purple
4 yellow
dtype: object
In [97]: obj3.reindex(range(6), method='ffill')
Out[97]:
0 blue
1 blue
2 purple
3 purple
4 yellow
5 yellow
dtype: object
method方法對(duì)于處理離散的數(shù)據(jù)好像還挺有用的,method插值可以是:
None:
'pad'/'ffill':用前面的數(shù)填充后面的數(shù)
‘backfill’/‘bfill’:用后面的數(shù)填充前面的數(shù)
‘nearest’:用最近的數(shù)填充
借助DataFrame,reindex可以修改(行)索引和列。只傳遞一個(gè)序列時(shí),會(huì)重新索引結(jié)果的行:
In [98]: frame = pd.DataFrame(np.arange(9).reshape((3, 3)),
....: index=['a', 'c', 'd'],
....: columns=['Ohio', 'Texas', 'California'])
In [99]: frame
Out[99]:
Ohio Texas California
a 0 1 2
c 3 4 5
d 6 7 8
In [100]: frame2 = frame.reindex(['a', 'b', 'c', 'd'])
In [101]: frame2
Out[101]:
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
借助DataFrame,reindex可以修改(行)索引和列。只傳遞一個(gè)序列時(shí),會(huì)重新索引結(jié)果的行:
In [98]: frame = pd.DataFrame(np.arange(9).reshape((3, 3)),
....: index=['a', 'c', 'd'],
....: columns=['Ohio', 'Texas', 'California'])
In [99]: frame
Out[99]:
Ohio Texas California
a 0 1 2
c 3 4 5
d 6 7 8
In [100]: frame2 = frame.reindex(['a', 'b', 'c', 'd'])
In [101]: frame2
Out[101]:
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
列可以用columns關(guān)鍵字重新索引:
In [102]: states = ['Texas', 'Utah', 'California']
In [103]: frame.reindex(columns=states)
Out[103]:
Texas Utah California
a 1 NaN 2
c 4 NaN 5
d 7 NaN 8
也就是說,DataFrame可以使用索引這一個(gè)工具進(jìn)行排序增刪操作,還是比較方便的。
表5-3列出了reindex函數(shù)的各參數(shù)說明。

基本上都是插值操作的參數(shù)。
文章代碼引用自:《利用Python進(jìn)行數(shù)據(jù)分析·第2版》第5章 Pandas入門
作者:SeanCheney
感謝SeanCheney同意引用。