溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么創(chuàng)建一個(gè)pandas多層索引

發(fā)布時(shí)間:2021-03-09 15:27:37 來源:億速云 閱讀:295 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)怎么創(chuàng)建一個(gè)pandas多層索引,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

多層索引的創(chuàng)建

普通-多個(gè)index創(chuàng)建

  • 在創(chuàng)建數(shù)據(jù)的時(shí)候加入一個(gè)index列表,這個(gè)index列表里面是多個(gè)索引列表

Series多層索引的創(chuàng)建方法

import pandas as pd
s = pd.Series([1,2,3,4,5,6],index=[['張三','張三','李四','李四','王五','王五'],
                  ['期中','期末','期中','期末','期中','期末']])
# print(s)
s

張三  期中    1
    期末    2
李四  期中    3
    期末    4
王五  期中    5
    期末    6
dtype: int64

利用 numpy中的隨機(jī)數(shù)

import numpy as np

data = np.random.randint(0,100,size=(6,3))
# np.random.randint(0,100,size=(6,3))是使用numpy中的隨機(jī)模塊random中,生成隨機(jī)整數(shù)方法randint,
# 里面的參數(shù)size是指定生成6行3列的數(shù)據(jù),并且每個(gè)數(shù)字的范圍在0到100之間

data
array([[44, 66, 67],
    [82, 52, 0],
    [34, 78, 23],
    [38, 4, 43],
    [60, 62, 40],
    [57, 9, 11]])

Dataframe多層索引創(chuàng)建

import pandas as pd
import numpy as np

data = np.random.randint(0,100,size=(6,3))
df = pd.DataFrame(data,index=[['張三','張三','李四','李四','王五','王五'],
               ['期中','期末','期中','期末','期中','期末']],
           columns=['Java','Web','Python'])

df

JavaWebPython
張三期中68490
期末336373
李四期中301368
期末141848
王五期中346626
期末891035

簡(jiǎn)化創(chuàng)建-from_product()

import pandas as pd
import numpy as np

data = np.random.randint(0,100,size=(6,3))
names = ['張三','李四','王五']
exam = ['期中','期末']
index = pd.MultiIndex.from_product([names,exam])
df = pd.DataFrame(data,index=index,columns=['Java','Web','Python'])
# print(df)
df

JavaWebPython
張三期中517847
期末395336
李四期中336083
期末90553
王五期中374566
期末68271

from_product()在這個(gè)里面的列表中位置不同, 產(chǎn)生的索引頁會(huì)不同

index = pd.MultiIndex.from_product([exam, names])
df = pd.DataFrame(data,index=index,columns=['Java','Web','Python'])
# print(df)
df

JavaWebPython
期中張三517847
李四395336
王五336083
期末張三90553
李四374566
王五68271

from_product([exam,names])會(huì)將列表中第一個(gè)元素作為最外層索引,依次類推

多層索引的取值

獲取到我們想要的數(shù)據(jù)

獲取多層索引Series中的數(shù)據(jù)

創(chuàng)建數(shù)據(jù)

import pandas as pd
s = pd.Series([1,2,3,4,5,6],index=[['張三','張三','李四','李四','王五','王五'],
                  ['期中','期末','期中','期末','期中','期末']])
print(s)

張三  期中    1
    期末    2
李四  期中    3
    期末    4
王五  期中    5
    期末    6
dtype: int64

可以直接使用[]的方式取最外面的一個(gè)層級(jí) s[‘張三']

s['李四']

# 注意:[]取值方式,不可直接使用最外層以外的其他層級(jí),例如:s['期末']

期中    3
期末    4
dtype: int64

使用['外索引', '內(nèi)索引'], 獲取某個(gè)數(shù)據(jù)

注意:[‘張三',‘期末']他們的順序不能變。剝洋蔥原則,從外到內(nèi)一層一層的剝。

s['李四', '期中'] # 李四期中分值

# 注意:['張三','期末']他們的順序不能變。剝洋蔥原則,從外到內(nèi)一層一層的剝。

3

使用[]的切片,獲取數(shù)據(jù)s[:,‘期中']

s[:,'期中'] # 第一個(gè)值為全部的外索引

張三    1
李四    3
王五    5
dtype: int64

使用 loc

  • loc 使用的是標(biāo)簽suoyin

  • iloc使用的是位置索引

# loc 使用方式與 [] 的方式基本一樣

s.loc['張三']
s.loc['張三','期中']
s.loc[:,'期中']

# iloc 的取值并不會(huì)受多層索引影響,只會(huì)根據(jù)數(shù)據(jù)的位置索引進(jìn)行取值, 不推薦

張三    1
李四    3
王五    5
dtype: int64

多層索引DataFrame的取值

在對(duì)多層索引DataFrame的取值是,推薦使用 loc() 函數(shù)

import pandas as pd
import numpy as np
#size參數(shù)是指定生成6行3列的數(shù)組
data = np.random.randint(0,100,size=(6,3))
names = ['張三','李四','王五']
exam = ['期中','期末']
index = pd.MultiIndex.from_product([names,exam])
df = pd.DataFrame(data,index=index,columns=['Java','Web','Python'])
df

JavaWebPython
張三期中34052
期末743885
李四期中72816
期末9250
王五期中13248
期末49461

三種方式都可以獲取張三期中各科成績(jī)

# df.loc['張三','期中']
# df.loc['張三'].loc['期中']
# df.loc[('張三','期中')]

注意:DataFrame中對(duì)行索引的時(shí)候和Series有一個(gè)同樣的注意點(diǎn),就是無法直接對(duì)二級(jí)索引直接進(jìn)行索引,必須讓二級(jí)索引變成一級(jí)索引后才能對(duì)其進(jìn)行索引

多層索引的排序

  • 使用sort_index() 排序

  • level參數(shù)可以指定是否按照指定的層級(jí)進(jìn)行排列

  • 第一層索引值為0, 第二層索引的值為1

創(chuàng)建數(shù)據(jù)

import pandas as pd
data = np.random.randint(0,100,size=(9,3))
key1 = ['b','c','a']
key2 = [2,1,3]
index = pd.MultiIndex.from_product([key1,key2])
df = pd.DataFrame(data,index=index,columns=['Java','Web','Python'])

df


JavaWebPython
b2568281
1841655
3352586
c276176
1362894
3797097
a2251730
1383878
3417590

排序

  • DataFrame按行索引排序的方法是sort_index()

  • 如果直接使用的話,不傳參數(shù), 會(huì)把每一層索引根據(jù)值進(jìn)行升序排序

df.sort_index()

JavaWebPython
a1186074
2668727
3961864
b1725852
2223122
3311283
c165496
294718
331634
# 當(dāng)level=0時(shí),ascending=False, 會(huì)根據(jù)第一層索引值進(jìn)行降序排序
df.sort_index(level=0,ascending=False)

JavaWebPython
c3797097
276176
1362894
b3352586
2568281
1841655
a3417590
2251730
1383878
# 當(dāng)level=1時(shí),會(huì)根據(jù)第二層索引值進(jìn)行降序排序

df.sort_index(level=1,ascending=False)

# 數(shù)據(jù)會(huì)根據(jù)第二層索引值進(jìn)行相應(yīng)的降序排列,
# 如果索引值相同時(shí)會(huì)根據(jù)其他層索引值排列

JavaWebPython
c3797097
b3352586
a3417590
c276176
b2568281
a2251730
c1362894
b1841655
a1383878

通過level設(shè)置排序的索引層級(jí),其他層索引也會(huì)根據(jù)其排序規(guī)則進(jìn)行排序

關(guān)于怎么創(chuàng)建一個(gè)pandas多層索引就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI