欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python?Pandas中l(wèi)oc和iloc函數(shù)的基本用法示例

 更新時(shí)間:2022年07月04日 16:22:07   作者:Apple-yeran  
無論是loc還是iloc都是pandas中數(shù)據(jù)篩選的函數(shù),下面這篇文章主要給大家介紹了關(guān)于Python?Pandas中l(wèi)oc和iloc函數(shù)的基本用法示例,文中通過示例代碼介紹的非常詳細(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表示行的編號(hào),columns表示列的編號(hào)
df = pd.DataFrame(np.random.randn(5, 2), index=range(0, 5, 1), columns=list('AB'))
print(df)

打印df的結(jié)果:

2.1 loc函數(shù)的用法

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

print(df.loc[0])

print(df.loc[0, :])

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

2.2 iloc函數(shù)的用法

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

print(df.iloc[0, :])

print(df.iloc[:, 0])

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

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

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

import numpy as np
import pandas as pd
#創(chuàng)建一個(gè)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ù):通過行號(hào)來取行數(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
 

總結(jié)

到此這篇關(guān)于Python Pandas中l(wèi)oc和iloc函數(shù)的基本用法的文章就介紹到這了,更多相關(guān)Pandas loc和iloc函數(shù)用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論