关于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'])

 

 

 

 

posted @ 2018-12-01 13:04  giaoxiao  阅读(65070)  评论(0编辑  收藏  举报