详谈Pandas中iloc和loc以及ix的区别

yipeiwu_com5年前Python基础

Pandas库中有iloc和loc以及ix可以用来索引数据,抽取数据。但是方法一多也容易造成混淆。下面将一一来结合代码说清其中的区别。

1. iloc和loc的区别:

iloc主要使用数字来索引数据,而不能使用字符型的标签来索引数据。而loc则刚好相反,只能使用字符型标签来索引数据,不能使用数字来索引数据,不过有特殊情况,当数据框dataframe的行标签或者列标签为数字,loc就可以来其来索引。

好,先上代码,先上行标签和列标签都为数字的情况。

import pandas as pd
import numpy as np
a = np.arange(12).reshape(3,4)
print a
>>>
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]
df = pd.DataFrame(a)
print df
>>>
 0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
print df.loc[0]
>>>
0 0
1 1
2 2
3 3
Name: 0, dtype: int32
print df.iloc[0]
0 0
1 1
2 2
3 3
Name: 0, dtype: int32
print df.loc[:,[0,3]]
 0 3
0 0 3
1 4 7
2 8 11
print df.iloc[:,[0,3]]
 0 3
0 0 3
1 4 7
2 8 11

接下来是把行标签[0, 1, 2]改成['a', 'b', 'c'],则成这样了。

df.index = ['a','b','c'] 
print df 
>>> 
 0 1 2 3 
a 0 1 2 3 
b 4 5 6 7 
c 8 9 10 11 
print df.loc[0] 
# TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <type 'int'> 
print df.iloc[0] 
>>> 
0 0 
1 1 
2 2 
3 3 
Name: a, dtype: int32 
print df.iloc['a'] # TypeError: cannot do positional indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [a] of <type 'str'> 
print df.loc['a'] # 正确 
>>> 
0 0 
1 1 
2 2 
3 3 
Name: a, dtype: int32 

同样地,把列标签[0, 1, 2, 3]改成['A', 'B, 'C', 'D'],则成这样了。

df.columns = ['A','B','C','D']
print df
>>>
 A B C D
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
print df.loc[:,'A']
>>>
a 0
b 4
c 8
Name: A, dtype: int32
print df.iloc[:,'A'] # ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types

2.ix是一种混合索引,字符型标签和整型数据索引都可以。

print df.ix[0]
>>>
A 0
B 1
C 2
D 3
Name: a, dtype: int32
print df.ix['a']
>>>
A 0
B 1
C 2
D 3
Name: a, dtype: int32
print df.ix[:,0]
>>>
a 0
b 4
c 8
Name: A, dtype: int32
print df.ix[:,'A']
>>>
a 0
b 4
c 8
Name: A, dtype: int32

以上这篇详谈Pandas中iloc和loc以及ix的区别就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在Django中实现添加user到group并查看

一、添加user到group 第一种: user.groups.add(1) # add by id 第二种: from django.contrib.auth.models...

Python中的map、reduce和filter浅析

1、先看看什么是 iterable 对象 以内置的max函数为例子,查看其doc:复制代码 代码如下:>>> print max.__doc__max(iterable...

Python实现拷贝多个文件到同一目录的方法

本文实例讲述了Python实现拷贝多个文件到同一目录的方法。分享给大家供大家参考,具体如下: 有一个文件,里面存有多个文件名,一个文件名一行。如果想把这些文件拷贝到一个目录,可以用下面的...

python修改注册表终止360进程实例

本文实例讲述了python修改注册表终止360进程的实现方法。分享给大家供大家参考。 具体实现代码如下: import _winreg import os import shutil...

pygame游戏之旅 添加碰撞效果的方法

pygame游戏之旅 添加碰撞效果的方法

本文为大家分享了pygame游戏之旅的第7篇,供大家参考,具体内容如下 对car和障碍的宽高进行比较然后打印即可: if y < thing_starty + thing_he...