Python學習筆記:索引設置之set_index和reset_index


數據分析過程中,有時出於增強數據可讀性或其他原因,需要對數據表的索引值進行設定。

pandas 中,常用 set_index()reset_index() 這兩個方法進行索引設置。

一、set_index方法

1.介紹

set_index() 方法將 DataFrame 中的列轉化為行索引。

轉換之后,原來的列將不見,可以通過設置 drop 保留原來的列。

使用語法為:

DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)

參數解釋:

keys -- 列標簽或列標簽/數組列表 需要設置為索引的列
drop -- 默認為True 刪除用作新索引的列
append -- 是否將列附加到現有索引 默認為False
inplace -- 布爾類型 表示當前操作是否對原數據生效 默認為False
verify_integrity -- 檢查新索引的副本 將其設置為False將提高該方法的性能 默認為false

2.實操

import pandas as pd
df = pd.DataFrame({'a':range(7),
                   'b':range(7,0,-1),
                   'c':['one','one','one','two','two','two','two'],
                   'd':[0,1,2,0,1,2,3]})

# 1.保留索引值
df.set_index(['c','d'], drop=False) 

# 2.添加到原有索引
df.set_index('c', append=True)

# 3.多重索引
df.set_index(['c','d'])

# 4.修改原數據框
df.set_index(['c','d'], inplace=True)

# 5.手動指定
df.set_index([pd.Index([1,2,3,4,5,6,7]), 'c'])

# 6.索引計算
s = pd.Series([1,2,3,4,5,6,7])
df.set_index([s, s**2])

二、reset_index方法

1.介紹

reset_index() 方法用於重新設置 DataFrame 索引。

使用語法為:

DataFrame.reset_index(level=None, drop=False, inpalce=False, col_level=0, col_fill=' ')

參數解釋:

level -- 數值類型 int、str、tuple或list 
         默認無 刪除所有級別的索引
         指定level 刪除指定級別
drop -- 當指定 drop=False 時,則索引列會被還原為普通列;否則,經設置后的新索引值被會丟棄 默認為False
inplace -- 布爾類型 是否修改原始數據框 默認False
col_level -- 數值類型 int、str 默認值為0
             如果列有多個級別,則確定將標簽插入到哪個級別。默認情況下,它將插入到第一級。
             (指定重置后的級別)
col_fill -- object 默認‘’,如果列有多個級別,則確定其他級別的命名方式。如果沒有,則重復索引名。

2.實操

import pandas as pd
import numpy as np
df = pd.DataFrame({'Country':['China','China', 'India', 'India', 'America', 'Japan', 'China', 'India'], 
                   'Income':[10000, 10000, 5000, 5002, 40000, 50000, 8000, 5000], 
                    'Age':[50, 43, 34, 40, 25, 25, 45, 32]})

df_new = df.set_index('Country', drop=True, append=False, inplace=False)

# 索引的列被還原
df_new.reset_index() # drop=False
df_new.reset_index(drop=True) # 列被刪除

# 原始數據框操作
df.reset_index(drop=True)
df.reset_index()

在原有的索引列重置索引,同時不另外添加新列。

常用於索引的重置,特別在進行數據刪減處理的時候派上用場。

df = pd.DataFrame(columns=['a', 'b'])
print(df)
print("---------")
b = pd.Series([1,1,1,1,1],index=[0,1,3,4,5])
a = pd.Series([2,2,2,2,2,2],index=[1,2,3,4,6,7])
df['a'] = a
df['b'] = b
print(df)

空數據框,只有列索引,沒有數據,引用 Series 數據時,不存在的 index 可能會出現 NaN 值,甚至出現錯誤提示:ValueError: cannot reindex from a duplicate axis 。此時需要 reset_index() 進行索引重置。

  • 復合索引 & 復合列名
# 構建
index = pd.MultiIndex.from_tuples([('bird', 'falcon'),
                                   ('bird', 'parrot'),
                                   ('mammal', 'lion'),
                                   ('mammal', 'monkey')],
                                  names=['class', 'name'])
columns = pd.MultiIndex.from_tuples([('speed', 'max'),
                                     ('species', 'type')])
df = pd.DataFrame([(389.0, 'fly'),
                   ( 24.0, 'fly'),
                   ( 80.5, 'run'),
                   (np.nan, 'jump')],
                  index=index,
                  columns=columns)
'''
               speed species
                 max    type
class  name                 
bird   falcon  389.0     fly
       parrot   24.0     fly
mammal lion     80.5     run
       monkey    NaN    jump
'''

# 等同於 level=0
df.reset_index(level='class') 

# col_level=1 指定重置后列的級別
df.reset_index(level='class', col_level=1)  

# col_fill 填充缺失的列級別
df.reset_index(level='class', col_level=0, col_fill='species') 

# 不存在的標簽 將被新建
df.reset_index(level='class', col_level=0, col_fill='xxx') 

reset_index()set_index() 方法可以無限制的交叉使用,靈活轉變 DataFrame 索引,以方便數據處理。

參考鏈接:pandas中的set_index( )函數

參考鏈接:如何在pandas中使用set_index( )與reset_index( )設置索引

參考鏈接:pandas.DataFrame.set_index

參考鏈接:pandas重置DataFrame或Series的索引index

參考鏈接:pandas.DataFrame.reset_index


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM