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

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

pandas學(xué)習(xí)之df.set_index的具體使用_python

作者:非昨 ? 更新時(shí)間: 2022-10-12 編程語(yǔ)言

處理數(shù)據(jù)時(shí),經(jīng)常需要對(duì)索引進(jìn)行處理,那么可以通過(guò)set_index和reset_index來(lái)進(jìn)行處理

官方文檔

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

參數(shù)解釋

構(gòu)建實(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è)置成索引的數(shù)據(jù),可以使一個(gè)標(biāo)簽,數(shù)組,或者標(biāo)簽或數(shù)組的列表

df.set_index('name')#指定某一列為索引

?? ?height?? ?weight
name?? ??? ?
小王?? ?178?? ??? ?156
小明?? ?171?? ??? ?90
小綠?? ?185?? ??? ?140
小紅?? ?196?? ??? ?142

drop:bool,default True

是否刪除作為索引使用的列,默認(rèn)True,即刪除做為索引的列

df.set_index('name',drop=False)

?? ??? ?height?? ?weight?? ?name
name?? ??? ??? ?
小王?? ?178?? ??? ?156?? ??? ?小王
小明?? ?171?? ??? ?90?? ??? ?小明
小綠?? ?185?? ??? ?140?? ??? ?小綠
小紅?? ?196?? ??? ?142?? ??? ?小紅

append:bool default False

將序列添加到索引中,形成多級(jí)序列

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

將結(jié)果返回為原變量

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#無(wú)需對(duì)df重新賦值,df即為上邊代碼的結(jié)果
?? ??? ??? ?height?? ?weight?? ?name
?? ?name?? ??? ??? ?
0?? ?小王?? ?178?? ??? ?156?? ??? ?小王
1?? ?小明?? ?171?? ??? ?90?? ??? ?小明
2?? ?小綠?? ?185?? ??? ?140?? ??? ?小綠
3?? ?小紅?? ?196?? ??? ?142?? ??? ?小紅

verify_integrity:bool default False

檢查索引是否重復(fù)。默認(rèn)是False。

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

欄目分類(lèi)
最近更新