#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')
從新索引行spa
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
states=['Texas','Utah','California'] frame.reindex(columns=states)
同時對行和列進行從新索引code
frame.reindex(index=['a','b','c','d'],columns=states).ffill()
利用ix的標籤索引功能,從新索引任務能夠變得更簡潔:對象
frame.ix[['a','b','c','d'],states]
問題記錄:blog
在同時對行和列進行索引時,書中代碼是:索引
frame.reindex(index=['a','b','c','d'],method='ffill',columns=states)
可是會出現錯誤:pandas
ValueError: index must be monotonic increasing or decreasing
#不加ffill填充 frame.reindex(index=['a','b','c','d'],columns=states)
結果爲it
查找資料後本身初步理解爲:爲了從新索引方法,你的索引必須是有序/單調/遞增的順序,由於列也是從新索引的,而不是單調增長或減小。io
書中的代碼適合之前版本的pandas。class
資料連接: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()
上面寫法能夠達到與書中一樣的結果。