pandas中按行索引数据loc,iloc,ix解析
2018-06-19 本文已影响8人
Adiwy
首先我们先初始化一个dataframe,作为我们的测试数据,方便我们解析:
data=pd.DataFrame(np.random.rand(10,5),index=[100,99,98,97,96,1,2,3,4,5])
数据的结果如下图所示

看到数据以后,我们需要明确一个事情,就是为什么要使用loc,iloc和ix这样的索引方式,我们使用如下的方式打印data
data[1]
输出结果

从上图可以看出输出结果为第二列的data值,但是当我们对data做切片处理(slice)后,请看输出结果
data[1:3]

输出结果变为按照行进行索引输出了,为了在任何情况下输出都是明确的,(记住明确的比含糊的好!)所以采用loc,iloc和ix方式对行进行索引,下面对这三种索引方式的输出结果放在下面,然后再解释区别
data.loc[1:3]

data.iloc[1:3]

data.ix[1:3]

三个索引方式的解析,我看到网上有一段很清晰的解释,贴在下面:
- loc 在index的标签上进行索引,范围包括start和end.
- iloc 在index的位置上进行索引,不包括end.
- ix 先在index的标签上索引,索引不到就在index的位置上索引(如果index非全整数),不包括end.
结合这段输出再看看上面的输出结果,三个索引所表达的意思很明显,这里要对第三个ix做一下解释,如果index非全整数,代表index索引不是标准的整数,有可能是字符串的索引,如下所示
data=pd.DataFrame(np.random.rand(10,5),index=['a','b','c','d','e',1,2,3,4,5])
data的结果如下图所示,注意标红的区域:

我们再执行
data.ix[1:3]
执行结果就会发生变化,如下图所示:

应为ix的这种特殊机制,我前面提到,明确的比含糊的好,所以我们在写代码的时候一定要优先使用loc和iloc!