關於python中loc和iloc方法


pandas以類似字典的方式來獲取某一列的值

import pandas as pd

import numpy as np

table = pd.DataFrame(np.zeros((4,2)), index=['a','b','c','d'], columns=['left', 'right'])

print(table)

得到:

如果我們此時需要得到table列的值

例如:table['left']

即可得到:

如果我們對於行感興趣,這時候有兩種方法,即 iloc 和 loc 方法

loc是指location的意思,iloc中的i是指integer。這兩者的區別如下:

  • loc works on labels in the index.
  • iloc works on the positions in the index (so it only takes integers)

也就是說loc是根據index來索引,

如上table定義了一個index,那么loc就根據這個index來索引對應的行。

iloc是根據行號來索引,行號從0開始,逐次加1。

例如:

print(table.iloc[0])

print(table.loc['a'])

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM