日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

pandas學習之df.set_index的具體使用_python

作者:非昨 ? 更新時間: 2022-10-12 編程語言

處理數據時,經常需要對索引進行處理,那么可以通過set_index和reset_index來進行處理

官方文檔

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

參數解釋

構建實例

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

需要設置成索引的數據,可以使一個標簽,數組,或者標簽或數組的列表

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。

原文鏈接:https://blog.csdn.net/lisnyuan/article/details/107086094

欄目分類
最近更新