重新索引
pandas對象的一個重要方法是
reindex ,其作用是創建一個適應新索引的新對象。
#reindex函數的參數 reindex(index,method,fill_value,limit,level,copy) #index:用作索引的新序列 #method:插值(填充)方式 #fill_value:在重新索引的過程中,需要引入缺失值時使用的代替值 #limit:前向或后向填充時的最大填充量 #level:在MultiIndex的指定級別上匹配簡單索引,否則選取其子集 #copy:默認為True,無論如何都復制,如果為False,則新舊相等就不復制
obj=Series([4.5,7.2,-5.3,3.6],index=['d','b','a','c']) obj #調用該Series的reindex將會根據新索引進行重排 #如果某個索引值當前不存在,就引入缺失值 obj2=obj.reindex(['a','b','c','d','e']) obj2 #填充缺失值 obj.reindex(['a','b','c','d','e'],fill_value=0)
重新索引時,可能需要做一些插值處理。method選項可以達到此目的。
obj3=Series(['blue','purple','yellow'],index=[0,2,4]) obj3 obj3.reindex(range(6),method='ffill')
reindex的(插值)method選項
ffill或pad ——向前填充(或搬運)值
bfill或backfill——后向填充(或搬運)值
重新索引行
frame=DataFrame(np.arange(9).reshape(3,3),index=['a','c','d'], columns=['Ohio','Texas','California']) frame frame2=frame.reindex(['a','b','c','d']) frame2
重新索引列
使用
columns關鍵字進行重新索引
states=['Texas','Utah','California'] frame.reindex(columns=states)
同時對行和列進行重新索引
frame.reindex(index=['a','b','c','d'],columns=states).ffill()
利用ix的標簽索引功能,重新索引任務可以變得更簡潔:
frame.ix[['a','b','c','d'],states]
問題記錄:
在同時對行和列進行索引時,書中代碼是:
frame.reindex(index=['a','b','c','d'],method='ffill',columns=states)
但是會出現錯誤:
ValueError: index must be monotonic increasing or decreasing
#不加ffill填充 frame.reindex(index=['a','b','c','d'],columns=states)
結果為
查找資料后自己初步理解為:為了重新索引方法,你的索引必須是有序/單調/遞增的順序,因為列也是重新索引的,而不是單調增加或減少。
書中的代碼適合以前版本的pandas。
資料鏈接:https://stackoverflow.com/questions/44868877/valueerror-index-must-be-monotonic-increasing-or-decreasing-including-index-co/46893526#46893526
解決:
frame.reindex(index=['a','b','c','d'],columns=states).ffill()
上面寫法可以達到與書中同樣的結果。