欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

pandas中DataFrame重置索引的幾種方法

 更新時間:2021年05月24日 14:20:31   作者:Jayson  
在pandas中,經(jīng)常對數(shù)據(jù)進行處理 而導致數(shù)據(jù)索引順序混亂,從而影響數(shù)據(jù)讀取、插入等,所以小編總結了幾種索引重置的方法,需要的朋友們下面隨著小編來一起學習學習吧

在pandas中,經(jīng)常對數(shù)據(jù)進行處理 而導致數(shù)據(jù)索引順序混亂,從而影響數(shù)據(jù)讀取、插入等。

小筆總結了以下幾種重置索引的方法:

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

# 對其重排順序,得到索引順序倒序的數(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

下面對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表示刪除原索引,不然會在數(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是第一個參數(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ù)結構上新建行(index是新索引,若新建數(shù)據(jù)索引在原數(shù)據(jù)中存在,則引用原有數(shù)據(jù)),默認用NaN填充(使用fill_value=0 來修改填充值自定義,此處我設置的是0)。
# df = df.reindex(columns=[]),在原數(shù)據(jù)結構上新建列,方法與新建行一樣

法四:

df2 = df2.set_index(keys=['a', 'c'])  # 將原數(shù)據(jù)a, c列的數(shù)據(jù)作為索引。
# drop=True,默認,是將數(shù)據(jù)作為索引后,在表格中刪除原數(shù)據(jù)
# 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

到此這篇關于pandas中DataFrame重置索引的幾種方法的文章就介紹到這了,更多相關pandas DataFrame重置索引內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論