1. 將 df 中的列設置成索引:
df.set_index(keys, drop=True, append=False, inplace=False,verify_integrity=False)
keys:接收 list,指定要設置成索引的列;
drop:默認為True,刪除作為新索引的列,否則不刪除;
append:追加新的索引值,默認 false 不追加;
inplace:是否修改原數據,默認 false 複製並修改新對象,true 時修改原數據。
verify_integrity:檢查新索引是否有重複項。
2. 重置索引,將索引變成列,並補上常規的數字索引:
df.reset_index(level=None, drop=False, inplace=False, col_level=0,col_fill='')
level:int、 str、tuple或list,默認為none,僅從索引中移除給定的級別。默認情況下刪除所有級別。
drop:bool,默認為 false,索引列(被設置為索引的列)被還原為普通列,並將索引重置為整數索引,否則直接丟棄索引列。
inplace:是否修改原數據,默認 false 複製並修改新對象,true時修改原數據。
col_level:int或str,默認為0,如果列有多個級別,則確定將標籤插入到哪個級別。默認情況下,它將插入第一個級別。
col_fill:對象,默認值”,如果列有多個級別,則確定其他級別的命名方式。如果沒有,則重複索引名。
範例:
#創建數據 data = pd.DataFrame(data=[['bar','one','z','1'], ['bar','two','v','2'], ['foo','one','x','3'], ['foo','two','w','4']]) out: 0 1 2 3 0 bar one z 1 1 bar two v 2 2 foo one x 3 3 foo two w 4 #強制修改列名 data.columns = ['a','b','c','d'] out: a b c d 0 bar one z 1 1 bar two v 2 2 foo one x 3 3 foo two w 4 #將c列設置為索引,並替換掉原來的數字索引 data.set_index('c') out: a b d c z bar one 1 v bar two 2 x foo one 3 w foo two 4 #將索引列重置為列 data.reset_index() out: a b d c z bar one 1 v bar two 2 x foo one 3 w foo two 4 #將c列設置為索引,並以追加的方式添加為二級索引 data.set_index('c',append=True) out: a b d c 0 z bar one 1 1 v bar two 2 2 x foo one 3 3 w foo two 4 #將追加的二級索引(level為1)還原成列 data.reset_index(level=1) out: c a b d 0 z bar one 1 1 v bar two 2 2 x foo one 3 3 w foo two 4 #level默認none,將所有索引(包括初始數字索引)設置為列,並再次初始化一個新的數字索引。 data.reset_index() out: level_0 c a b d 0 0 z bar one 1 1 1 v bar two 2 2 2 x foo one 3 3 3 w foo two 4