Pandas 多層索引轉化為列


處理原因

當DataFrame使用分組聚合后,分組的規則會作為索引,如下例。為了便於后續對表格數據的處理和分析,可將索引轉化為列。

數據樣式

# 各地區分店每年的銷售額
sales_area = df.groupby(['Market','Order_Year'])['Sales'].sum()
# 當前sales_area有多層索引
sales_area

使用reset_index()函數將索引轉換為列

reset_index()函數

pandas.DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')
參數:
level:int,str,tuple,or list,default None
僅從索引中刪除輸入的級別,默認刪除全部索引
drop:bool,default False
不會將刪除的索引轉化成列,默認是False:轉化成列;True:刪除的索引直接丟棄,不轉化成列
inplace:bool,defualt False
是否在原數據上做更改,默認False:不在源數據上做更改,此時有返回值DataFrame需要變量進行賦值;True無返回值
col_level
col_fill
返回值:DataFrame或None(取決於參數inplace的值)

pandas.Series.reset_index(level=None, drop=False, name=None, inplace=False)
參數:
level
drop
name:object,str
對原數據列的列名字進行更改,當drop為False才能使用本參數
inplace
當drop為False時,返回DataFrame類型,由於原數據類型是Series,返回值類型和原數據類型不同,故不能在原數據上更改,inplace只能是False;當drop為True時,返回series類型,此時inplace=True可在原數據上更改
返回值:Series or DataFrame or None(取決於參數drop和inpalce的值)

錯誤示例

# 各地區分店每年的銷售額
sales_area = df.groupby(['Market','Order_Year'])['Sales'].sum()
# 將索引轉化為列
sales_area.reset_index(inplace=True)
sales_area

報錯:TypeError: Cannot reset_index inplace on a Series to create a DataFrame

正確轉化

由於返回值是DataFrame類型,原數據是Series類型,故此時不能在原數據上更改。修改如下:

# 各地區分店每年的銷售額
sales_area = df.groupby(['Market','Order_Year'])['Sales'].sum()
# 將索引轉化為列
sales_area=sales_area.reset_index()
sales_area


免責聲明!

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



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