在pandas中,經常對數據進行處理 而導致數據索引順序混亂,從而影響數據讀取、插入等。
小筆總結了以下幾種重置索引的方法:
import pandas as pd import numpy as np df = pd.DataFrame(np.arange(20).reshape((5, 4)),columns=['a', 'b', 'c', 'd']) #得到df: a b c d 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 3 12 13 14 15 4 16 17 18 19 # 對其重排順序,得到索引順序倒序的數據 df2 = df.sort_values('a', ascending=False) # 得到df2: a b c d 4 16 17 18 19 3 12 13 14 15 2 8 9 10 11 1 4 5 6 7 0 0 1 2 3
下面對df2重置索引,使其索引從0開始
法一:
簡單粗暴:
df2.index = range(len(df2))
# 輸出df2: a b c d 0 16 17 18 19 1 12 13 14 15 2 8 9 10 11 3 4 5 6 7 4 0 1 2 3
法二:
df2 = df2.reset_index(drop=True) # drop=True表示刪除原索引,不然會在數據表格中新生成一列'index'數據 # 輸出df2: a b c d 0 16 17 18 19 1 12 13 14 15 2 8 9 10 11 3 4 5 6 7 4 0 1 2 3
法三:
df2 = df2.reindex(labels=range(len(df)) #labels是第一個參數,可以省略 # 輸出df2 a b c d 0 16 17 18 19 1 12 13 14 15 2 8 9 10 11 3 4 5 6 7 4 0 1 2 3 # 注:df = df.reindex(index=[]),在原數據結構上新建行(index是新索引,若新建數據索引在原數據中存在,則引用原有數據),默認用NaN填充(使用fill_value=0 來修改填充值自定義,此處我設置的是0)。 # df = df.reindex(columns=[]),在原數據結構上新建列,方法與新建行一樣
法四:
df2 = df2.set_index(keys=['a', 'c']) # 將原數據a, c列的數據作為索引。 # drop=True,默認,是將數據作為索引后,在表格中刪除原數據 # append=False,默認,是將新設置的索引設置為內層索引,原索引是外層索引 # 輸出df2,注意a,c列是索引: b d a c 16 18 17 19 12 14 13 15 8 10 9 11 4 6 5 7 0 2 1 3
