在pandas中,經(jīng)常對(duì)數(shù)據(jù)進(jìn)行處理 而導(dǎo)致數(shù)據(jù)索引順序混亂,從而影響數(shù)據(jù)讀取、插入等。
小筆總結(jié)了以下幾種重置索引的方法:
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 # 對(duì)其重排順序,得到索引順序倒序的數(shù)據(jù) 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
下面對(duì)df2重置索引,使其索引從0開(kāi)始
法一:
簡(jiǎn)單粗暴:
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表示刪除原索引,不然會(huì)在數(shù)據(jù)表格中新生成一列'index'數(shù)據(jù) # 輸出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是第一個(gè)參數(shù),可以省略 # 輸出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=[]),在原數(shù)據(jù)結(jié)構(gòu)上新建行(index是新索引,若新建數(shù)據(jù)索引在原數(shù)據(jù)中存在,則引用原有數(shù)據(jù)),默認(rèn)用NaN填充(使用fill_value=0 來(lái)修改填充值自定義,此處我設(shè)置的是0)。 # df = df.reindex(columns=[]),在原數(shù)據(jù)結(jié)構(gòu)上新建列,方法與新建行一樣
法四:
df2 = df2.set_index(keys=['a', 'c']) # 將原數(shù)據(jù)a, c列的數(shù)據(jù)作為索引。 # drop=True,默認(rèn),是將數(shù)據(jù)作為索引后,在表格中刪除原數(shù)據(jù) # append=False,默認(rèn),是將新設(shè)置的索引設(shè)置為內(nèi)層索引,原索引是外層索引 # 輸出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
到此這篇關(guān)于pandas中DataFrame重置索引的幾種方法的文章就介紹到這了,更多相關(guān)pandas DataFrame重置索引內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:銅川 常德 阿里 株洲 通遼 黑龍江 潛江 呂梁
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《pandas中DataFrame重置索引的幾種方法》,本文關(guān)鍵詞 pandas,中,DataFrame,重置,索引,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。