標籤:oat 3.0 dex post src gpo blog order width
準系統重新索引Series的reindex方法
In [15]: obj = Series([3,2,5,7,6,9,0,1,4,8],index=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘, ...: ‘h‘,‘i‘,‘j‘])In [16]: obj1 = obj.reindex([‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘,‘h‘,‘i‘,‘j‘,‘k‘])In [17]: obj1Out[17]:a 3.0b 2.0c 5.0d 7.0e 6.0f 9.0g 0.0h 1.0i 4.0j 8.0k NaNdtype: float64
新索引值當前值缺失,則需要插值
前向值填充method=’ffill’,最後索引j對應的值來填充
In [19]: obj1 = obj.reindex([‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘,‘h‘,‘i‘,‘j‘,‘k‘],metho ...: d=‘ffill‘)In [20]: obj1Out[20]:a 3b 2c 5d 7e 6f 9g 0h 1i 4j 8k 8dtype: int64
前向值搬運method=’pad’,最後索引j對應的值來填充
In [23]: obj1 = obj.reindex([‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘,‘h‘,‘i‘,‘j‘,‘k‘],metho ...: d=‘pad‘)In [24]: obj1Out[24]:a 3b 2c 5d 7e 6f 9g 0h 1i 4j 8k 8dtype: int64
後向值填充method=’bfill’,最後索引j的後面的索引對應的值來填充,j的後一個位置為NaN的空行
In [62]: obj2 = obj.reindex([‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘,‘k‘,‘h‘,‘i‘,‘j‘],metho
...: d=‘bfill‘)
In [63]: obj2
Out[63]:
a 3.0
b 2.0
c 5.0
d 7.0
e 6.0
f 9.0
g 0.0
k NaN
h 1.0
i 4.0
j 8.0
dtype: float64
後向值搬運method=’backfill’,最後索引j的後面的索引對應的值來填充,j的後一個位置為NaN的空行
In [64]: obj2 = obj.reindex([‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘,‘k‘,‘h‘,‘i‘,‘j‘],metho ...: d=‘backfill‘)In [65]: obj2Out[65]:a 3.0b 2.0c 5.0d 7.0e 6.0f 9.0g 0.0k NaNh 1.0i 4.0j 8.0dtype: float64
DataFrame的reindex方法
修改(行)索引、列,或兩個都修改。
引入一個序列,則重新索引行,如下:
In [86]: data = {‘class‘:[‘語文‘,‘數學‘,‘英語‘],‘score‘:[120,130,140]}In [87]: frame = DataFrame(data)In [88]: frameOut[88]: class score0 語文 1201 數學 1302 英語 140In [89]: frame2 = frame.reindex([0,1,2,3])In [90]: frame2Out[90]: class score0 語文 120.01 數學 130.02 英語 140.03 NaN NaN
行、列 都修改
In [94]: frame3 = frame.reindex(index=[11,22,33],columns = [‘a‘,‘b‘,‘c‘,‘d‘])In [95]: frame3Out[95]: a b c d11 NaN NaN NaN NaN22 NaN NaN NaN NaN33 NaN NaN NaN NaN
reindex的參數如下:
刪除指定軸(索引)上的項Series
In [112]: obj = Series([1,2,3,4],index=[‘a‘,‘b‘,‘c‘,‘d‘])In [113]: objOut[113]:a 1b 2c 3d 4dtype: int64In [114]: obj1 = obj.drop(‘c‘)In [115]: obj1Out[115]:a 1b 2d 4dtype: int64
DataFrame
刪除單索引行
In [109]: frameOut[109]: class score0 語文 1201 數學 1302 英語 140In [110]: obj = frame.drop(0)In [111]: objOut[111]: class score1 數學 1302 英語 140
刪除多索引行
In [119]: frameOut[119]: class score0 語文 1201 數學 1302 英語 140In [120]: frame.drop([1,2])Out[120]: class score0 語文 120
刪除多索引行(帶axis)
In [130]: frameOut[130]: class score0 語文 1201 數學 1302 英語 140In [131]: frame.drop([1,2],axis=0)Out[131]: class score0 語文 120
刪除列(columns)(帶axis)
In [135]: frameOut[135]: class score0 語文 1201 數學 1302 英語 140In [136]: frame.drop([‘class‘],axis=1)Out[136]: score0 1201 1302 140
其中,axis=0,表示行,axis=1,表示列
利用Python進行資料分析_Pandas_基礎_2