pandas學習之df.set_index的具體使用
處理數(shù)據(jù)時,經(jīng)常需要對索引進行處理,那么可以通過set_index和reset_index來進行處理
官方文檔
DataFrame.set_index(self, keys, drop=True, append=False, inplace=False, verify_integrity=False)
參數(shù)解釋
構建實例
import pandas as pd df = pd.DataFrame(data={'height':[178,171,185,196],'weight':[156,90,140,142], ?? ??? ??? ??? ??? ??? ?'name':['小王','小明','小綠','小紅']}) df ?? ?height?? ?weight?? ?name 0?? ?178?? ??? ?156?? ??? ?小王 1?? ?171?? ??? ?90?? ??? ?小明 2?? ?185?? ??? ?140?? ??? ?小綠 3?? ?196?? ??? ?142?? ??? ?小紅
key:label array-like or list of label/arrays
需要設置成索引的數(shù)據(jù),可以使一個標簽,數(shù)組,或者標簽或數(shù)組的列表
df.set_index('name')#指定某一列為索引 ?? ?height?? ?weight name?? ??? ? 小王?? ?178?? ??? ?156 小明?? ?171?? ??? ?90 小綠?? ?185?? ??? ?140 小紅?? ?196?? ??? ?142
drop:bool,default True
是否刪除作為索引使用的列,默認True,即刪除做為索引的列
df.set_index('name',drop=False) ?? ??? ?height?? ?weight?? ?name name?? ??? ??? ? 小王?? ?178?? ??? ?156?? ??? ?小王 小明?? ?171?? ??? ?90?? ??? ?小明 小綠?? ?185?? ??? ?140?? ??? ?小綠 小紅?? ?196?? ??? ?142?? ??? ?小紅
append:bool default False
將序列添加到索引中,形成多級序列
df.set_index(df['name'],append = True) ? ? ? ? ? ? height?? ?weight?? ?name ?? ?name?? ??? ??? ? 0?? ?小王?? ?178?? ??? ?156?? ??? ?小王 1?? ?小明?? ?171?? ??? ?90?? ??? ?小明 2?? ?小綠?? ?185?? ??? ?140?? ??? ?小綠 3?? ?小紅?? ?196?? ??? ?142?? ??? ?小紅 # 前兩列都為索引
inplace:bool default False
將結果返回為原變量
df#原df ?? ?height?? ?weight?? ?name 0?? ?178?? ??? ?156?? ??? ?小王 1?? ?171?? ??? ?90?? ??? ?小明 2?? ?185?? ??? ?140?? ??? ?小綠 3?? ?196?? ??? ?142?? ??? ?小紅 df.set_index(df['name'],append = True,inplace = True) ?? ??? ??? ?height?? ?weight?? ?name ?? ?name?? ??? ??? ? 0?? ?小王?? ?178?? ??? ?156?? ??? ?小王 1?? ?小明?? ?171?? ??? ?90?? ??? ?小明 2?? ?小綠?? ?185?? ??? ?140?? ??? ?小綠 3?? ?小紅?? ?196?? ??? ?142?? ??? ?小紅 df#無需對df重新賦值,df即為上邊代碼的結果 ?? ??? ??? ?height?? ?weight?? ?name ?? ?name?? ??? ??? ? 0?? ?小王?? ?178?? ??? ?156?? ??? ?小王 1?? ?小明?? ?171?? ??? ?90?? ??? ?小明 2?? ?小綠?? ?185?? ??? ?140?? ??? ?小綠 3?? ?小紅?? ?196?? ??? ?142?? ??? ?小紅
verify_integrity:bool default False
檢查索引是否重復。默認是False。
到此這篇關于pandas學習之df.set_index的具體使用的文章就介紹到這了,更多相關pandas df.set_index內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- pandas 強制類型轉換 df.astype實例
- pandas || df.dropna() 缺失值刪除操作
- pandas數(shù)據(jù)選?。篸f[] df.loc[] df.iloc[] df.ix[] df.at[] df.iat[]
- Pandas數(shù)據(jù)形狀df.shape的實現(xiàn)
- Pandas索引排序 df.sort_index()的實現(xiàn)
- Pandas缺失值刪除df.dropna()的使用
- Pandas數(shù)據(jù)類型轉換df.astype()及數(shù)據(jù)類型查看df.dtypes的使用
- Pandas中df.loc[]與df.iloc[]的用法與異同?
相關文章
django框架使用views.py的函數(shù)對表進行增刪改查內(nèi)容操作詳解【models.py中表的創(chuàng)建、views.py中
這篇文章主要介紹了django框架使用views.py的函數(shù)對表進行增刪改查內(nèi)容操作,結合實例形式詳細分析了models.py中表的創(chuàng)建、views.py中函數(shù)的使用,基于對象的跨表查詢等相關操作技巧與使用注意事項,需要的朋友可以參考下2019-12-12Pytorch中torch.cat()函數(shù)的使用及說明
這篇文章主要介紹了Pytorch中torch.cat()函數(shù)的使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01python區(qū)塊鏈持久化和命令行接口實現(xiàn)簡版
這篇文章主要為大家介紹了python區(qū)塊鏈持久化和命令行接口實現(xiàn)簡版,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05