溫馨提示×

溫馨提示×

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

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

Python?Pandas中l(wèi)oc和iloc函數(shù)怎么使用

發(fā)布時間:2022-07-05 10:08:59 來源:億速云 閱讀:474 作者:iii 欄目:開發(fā)技術(shù)

今天小編給大家分享一下Python Pandas中l(wèi)oc和iloc函數(shù)怎么使用的相關(guān)知識點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

    1 loc和iloc的含義

    loc表示location的意思;iloc中的loc意思相同,前面的i表示integer,所以它只接受整數(shù)作為參數(shù)。

    2 用法

    import pandas as pd
    import numpy as np
    # np.random.randn(5, 2)表示返回5x2的矩陣,index表示行的編號,columns表示列的編號
    df = pd.DataFrame(np.random.randn(5, 2), index=range(0, 5, 1), columns=list('AB'))
    print(df)

    打印df的結(jié)果:

    Python?Pandas中l(wèi)oc和iloc函數(shù)怎么使用

    2.1 loc函數(shù)的用法

    loc表示通過標(biāo)簽取數(shù)據(jù),標(biāo)簽就是上面的‘0’-‘4’和‘A’-‘B’。

    print(df.loc[0])

    Python?Pandas中l(wèi)oc和iloc函數(shù)怎么使用

    print(df.loc[0, :])

    Python?Pandas中l(wèi)oc和iloc函數(shù)怎么使用

    print(df.loc[0:2, 'A'])

    Python?Pandas中l(wèi)oc和iloc函數(shù)怎么使用

    2.2 iloc函數(shù)的用法

    iloc函數(shù)表示通過位置取數(shù)據(jù),即第m行,第n列數(shù)據(jù),只接受整型參數(shù)。記?。?strong>0:2為“包左不包右”,即取0, 1。

    print(df.iloc[0, :])

    Python?Pandas中l(wèi)oc和iloc函數(shù)怎么使用

    print(df.iloc[:, 0])

    Python?Pandas中l(wèi)oc和iloc函數(shù)怎么使用

    print(df.iloc[0:2, :])

    Python?Pandas中l(wèi)oc和iloc函數(shù)怎么使用

    補(bǔ)充:Pandas中l(wèi)oc和iloc函數(shù)實(shí)例

    利用loc、iloc提取行數(shù)據(jù)

    import numpy as np
    import pandas as pd
    #創(chuàng)建一個Dataframe
    data=pd.DataFrame(np.arange(16).reshape(4,4),index=list('abcd'),columns=list('ABCD'))
     
    In[1]: data
    Out[1]: 
        A   B   C   D
    a   0   1   2   3
    b   4   5   6   7
    c   8   9  10  11
    d  12  13  14  15
     
    #取索引為'a'的行
    In[2]: data.loc['a']
    Out[2]:
    A    0
    B    1
    C    2
    D    3
     
    #取第一行數(shù)據(jù),索引為'a'的行就是第一行,所以結(jié)果相同
    In[3]: data.iloc[0]
    Out[3]:
    A    0
    B    1
    C    2
    D    3

    loc函數(shù):通過行索引 “Index” 中的具體值來取行數(shù)據(jù)(如取"Index"為"A"的行)

    iloc函數(shù):通過行號來取行數(shù)據(jù)(如取第二行的數(shù)據(jù))

    利用loc、iloc提取列數(shù)據(jù)

    In[4]:data.loc[:,['A']] #取'A'列所有行,多取幾列格式為 data.loc[:,['A','B']]
    Out[4]: 
        A
    a   0
    b   4
    c   8
    d  12
     
    In[5]:data.iloc[:,[0]] #取第0列所有行,多取幾列格式為 data.iloc[:,[0,1]]
    Out[5]: 
        A
    a   0
    b   4
    c   8
    d  12

    以上就是“Python Pandas中l(wèi)oc和iloc函數(shù)怎么使用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注億速云行業(yè)資訊頻道。

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

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

    AI