首先,介绍这三种方法的概述:

loc: loc gets rows (or columns) with particular labels from the index. loc从索引中获取具有特定标签的行(或列)。这里的关键是:标签。标签的理解就是name名字。

iloc: gets rows (or columns) at particular positions in the index (so it only takes integers). iloc在索引中的特定位置获取行(或列)(因此它只接受整数)。这里的关键是:位置。位置的理解就是排第几个。

ix: usually tries to behave like loc but falls back to behaving like iloc if a label is not present in the index. ix通常会尝试像loc一样行为,但如果索引中不存在标签,则会退回到像iloc一样的行为。

1.loc

其实,对于loc始终坚持一个原则:loc是基于label进行索引的!

import pandas as pd
df1 = pd.DataFrame(data= [[1, 2, 3],[4, 5, 6], [7, 8, 9]], index=[0, 1, 2], columns=['a','b','c'])
df2 = pd.DataFrame(data= [[1, 2, 3],[4, 5, 6], [7, 8, 9]], index=['e', 'f', 'g'], columns=['a','b','c'])
print(df1)
print(df2)
'''
df1:a  b  c
0  1  2  3
1  4  5  6
2  7  8  9
df2:a  b  c
e  1  2  3
f  4  5  6
g  7  8  9
'''# loc索引行,label是整型数字
print(df1.loc[0])
'''
a    1
b    2
c    3
Name: 0, dtype: int64
'''# loc索引行,label是字符型
print(df2.loc['e'])
'''
a    1
b    2
c    3
Name: 0, dtype: int64
'''
# 如果对df2这么写:df2.loc[0]会报错,因为loc索引的是label,显然在df2的行的名字中没有叫0的。
print(df2.loc[0])
'''
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <class 'int'>
'''# loc索引多行数据
print(df1.loc[1:])
'''a  b  c
1  4  5  6
2  7  8  9
'''# loc索引多列数据
print(df1.loc[:,['a', 'b']])
'''a  b
0  1  2
1  4  5
2  7  8
'''

# df1.loc[:,0:2]这么写报错, 因为loc索引的是label,显然在df1的列的名字中没有叫0,1和2的。
print(df1.loc[:,0:2])
'''
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <class 'int'>
'''# locs索引某些行某些列
print(df1.loc[0:2, ['a', 'b']])
'''a  b
0  1  2
1  4  5
2  7  8
'''

2.iloc

对于iloc始终也坚持一个原则:iloc是基于position进行索引的!

import pandas as pd
df1 = pd.DataFrame(data= [[1, 2, 3],[4, 5, 6], [7, 8, 9]], index=[0, 1, 2], columns=['a','b','c'])
df2 = pd.DataFrame(data= [[1, 2, 3],[4, 5, 6], [7, 8, 9]], index=['e', 'f', 'g'], columns=['a','b','c'])
print(df1)
print(df2)
'''
df1:a  b  c
0  1  2  3
1  4  5  6
2  7  8  9
df2:a  b  c
e  1  2  3
f  4  5  6
g  7  8  9
'''

# iloc索引行,label是整型数字
print(df1.iloc[0])
'''
a    1
b    2
c    3
Name: 0, dtype: int64
'''# iloc索引行,label是字符型。如果按照loc的写法来写应该是:df2.iloc['e'],显然这样报错,因为iloc不认识label,它是基于位置的。
print(df2.iloc['e'])
'''
TypeError: cannot do positional indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [e] of <class 'str'>
'''

# iloc索引行,label是字符型。正确的写法应该如下:
# 也就说,不论index是什么类型的,iloc只能写位置,也就是整型数字。
print(df2.iloc[0])
'''
a    1
b    2
c    3
Name: e, dtype: int64
'''# iloc索引多行数据
print(df1.iloc[1:])
'''a  b  c
1  4  5  6
2  7  8  9
'''# iloc索引多列数据
# 如果如下写法,报错。
print(df1.iloc[:,['a', 'b']])
'''
TypeError: cannot perform reduce with flexible type
'''

# iloc索引多列数据, 正确写法如下:
print(df1.iloc[:,0:2])
'''a  b
0  1  2
1  4  5
2  7  8
'''# iloc索引某些行某些列
print(df1.iloc[0:2, 0:1])
'''a
0  1
1  4
'''

3.ix

注:ix的操作比较复杂,在pandas版本0.20.0及其以后版本中,ix已经不被推荐使用,建议采用iloc和loc实现ix。

(1)如果索引是整数类型,则ix将仅使用基于标签的索引,而不会回退到基于位置的索引。如果标签不在索引中,则会引发错误。

(2)如果索引不仅包含整数,则给定一个整数,ix将立即使用基于位置的索引而不是基于标签的索引。但是,如果ix被赋予另一种类型(例如字符串),则它可以使用基于标签的索引。

接下来举例说明这两个特点:

>>> s = pd.Series(np.nan, index=[49,48,47,46,45, 1, 2, 3, 4, 5])
>>> s
49   NaN
48   NaN
47   NaN
46   NaN
45   NaN
1    NaN
2    NaN
3    NaN
4    NaN
5    NaN

现在我们来看使用整数3切片有什么结果:

在这个例子中,s.iloc[:3]读取前3行(因为iloc把3看成是位置position),而s.loc[:3]读取的是前8行(因为loc把3看作是索引的标签label)

>>> s.iloc[:3] # slice the first three rows
49   NaN
48   NaN
47   NaN>>> s.loc[:3] # slice up to and including label 3
49   NaN
48   NaN
47   NaN
46   NaN
45   NaN
1    NaN
2    NaN
3    NaN>>> s.ix[:3] # the integer is in the index so s.ix[:3] works like loc
49   NaN
48   NaN
47   NaN
46   NaN
45   NaN
1    NaN
2    NaN
3    NaN

注意:s.ix[:3]返回的结果与s.loc[:3]一样,这是因为如果series的索引是整型的话,ix会首先去寻找索引中的标签3而不是去找位置3。

如果,我们试图去找一个不在索引中的标签,比如说是6呢?

>>> s.iloc[:6]
49   NaN
48   NaN
47   NaN
46   NaN
45   NaN
1    NaN>>> s.loc[:6]
KeyError: 6>>> s.ix[:6]
KeyError: 6

在上面的例子中,s.iloc[:6]正如我们所期望的,返回了前6行。而,s.loc[:6]返回了KeyError错误,这是因为标签6并不在索引中。

那么,s.ix[:6]报错的原因是什么呢?正如我们在ix的特点1所说的那样,如果索引只有整数类型,那么ix仅使用基于标签的索引,而不会回退到基于位置的索引。如果标签不在索引中,则会引发错误。

如果我们的索引是一个混合的类型,即不仅仅包括整型,也包括其他类型,如字符类型。那么,给ix一个整型数字,ix会立即使用iloc操作,而不是报KeyError错误。

>>> s2 = pd.Series(np.nan, index=['a','b','c','d','e', 1, 2, 3, 4, 5])
>>> s2.index.is_mixed() # index is mix of different types
True
>>> s2.ix[:6] # now behaves like iloc given integer
a   NaN
b   NaN
c   NaN
d   NaN
e   NaN
1   NaN

注意:在这种情况下,ix也可以接受非整型,这样就是loc的操作:

>>> s2.ix[:'c'] # behaves like loc given non-integer
a   NaN
b   NaN
c   NaN

这个例子就说明了ix特点2。

正如前面所介绍的,ix的使用有些复杂。如果仅使用位置或者标签进行切片,使用iloc或者loc就行了,请避免使用ix。

4.在Dataframe中使用ix实现复杂切片

有时候,在使用Dataframe进行切片时,我们想混合使用标签和位置来对行和列进行切片。那么,应该怎么操作呢?

举例,考虑有下述例子中的Dataframe。我们想得到直到包含标签'c'的行和前4列。

>>> df = pd.DataFrame(np.nan, index=list('abcde'),columns=['x','y','z', 8, 9])
>>> dfx   y   z   8   9
a NaN NaN NaN NaN NaN
b NaN NaN NaN NaN NaN
c NaN NaN NaN NaN NaN
d NaN NaN NaN NaN NaN
e NaN NaN NaN NaN NaN

在pandas的早期版本(0.20.0)之前,ix可以很好地实现这个功能。

我们可以使用标签来切分行,使用位置来切分列(请注意:因为4并不是列的名字,因为ix在列上是使用的iloc)。

>>> df.ix[:'c', :4]x   y   z   8
a NaN NaN NaN NaN
b NaN NaN NaN NaN
c NaN NaN NaN NaN

在pandas的后来版本中,我们可以使用iloc和其它的一个方法就可以实现上述功能:

>>> df.iloc[:df.index.get_loc('c') + 1, :4]x   y   z   8
a NaN NaN NaN NaN
b NaN NaN NaN NaN
c NaN NaN NaN NaN

get_loc() 是得到标签在索引中的位置的方法。请注意,因为使用iloc切片时不包括最后1个点,因为我们必须加1。

可以看到,只使用iloc更好用,因为不必理会ix的那2个“繁琐”的特点。

参考文献:https://stackoverflow.com/questions/31593201/pandas-iloc-vs-ix-vs-loc-explanation-how-are-they-different

转载于https://blog.csdn.net/anshuai_aw1/article/details/82801435

转载于:https://www.cnblogs.com/RB26DETT/p/11557339.html

pandas之loc iloc ix相关推荐

  1. Pandas的 loc iloc ix 区别

    import pandas as pd data = [[1,2,3],[4,5,6]] index = [0,1] columns=['a','b','c'] df = pd.DataFrame(d ...

  2. pandas的loc, iloc, ix的操作

    参考: https://blog.csdn.net/xw_classmate/article/details/51333646 1. loc--通过行标签索引行数据 2. iloc--通过行号获取行数 ...

  3. 2017.06.15-2016.06.18回顾 loc/iloc/ix dataframe相关 oracle无自增去重 correl

    上周最后阶段比较忙,主要是忙jd的数据测试的事情还有就是各种新产品的事情,下面回顾一下这段时间的工作. 1.上周四快下班的时候开了一个新产品的会,初步确定了风控策略,但是接近下班的时候又告诉我另外一个 ...

  4. pandas loc iloc ix用法详解

    1.什么是label pandas处理数据时,我们会经常看到dataframe结构使用loc, iloc, ix等方法.那么这些方法到底有啥区别,下面我们来进行详细分析. 首先我们先明确一点,这几个方 ...

  5. python中loc什么意思_python pandas 中 loc iloc 用法区别

    转自:https://blog.csdn.net/qq_21840201/article/details/80725433 ### 随机生DataFrame 类型数据 import pandas as ...

  6. Python的数据科学函数包(二)——pandas(series dataframe)(loc iloc ix)(csv文件)

    pandas 1.pandas数据的存储相对来说比较简单,它就只有两种非常重要的数据类型,一种叫series,一种叫dataframe series是指那些一维的数据,dataframe是指那些二维的 ...

  7. pandas中loc、iloc与ix的用法比较

    目录导读: 数据示例 loc iloc ix 数据示例 loc loc 在index的标签上进行索引,范围包括start和end. iloc iloc 在index的位置上进行索引,不包括end. i ...

  8. pandas中DataFrame的ix,loc,iloc索引方式的异同

    pandas中DataFrame的ix,loc,iloc索引方式的异同 1.loc: 按照标签索引,范围包括start和end 2.iloc: 在位置上进行索引,不包括end 3.ix: 先在inde ...

  9. Pandas中iloc、loc、ix三者的区别

    一.综述:iloc.loc.ix可以用来索引数据.抽取数据 二.iloc.loc.ix三者对比 iloc和loc的区别 iloc主要使用数字来索引数据,不能使用字符型的标签来索引数据. loc只能使用 ...

最新文章

  1. OpenCV直线拟合检测
  2. STL中的map、unordered_map、hash_map
  3. xheditor 内容保存时 不转义html特殊字符,xheditor编辑器上传图片(示例代码)
  4. 以下用于数据存储领域的python第三方库是-『爬虫四步走』手把手教你使用Python抓取并存储网页数据!...
  5. Ruby版本管理(RVM)
  6. 【AI不惑境】网络的宽度如何影响深度学习模型的性能?
  7. js 用迭代器模式优雅的处理递归问题
  8. 判断字符是否在1-15之间
  9. underscore源码学习笔记(一)
  10. 几个免费的中文分词模块
  11. 移动硬盘文件或目录损坏且无法读取要怎么办啊
  12. web前端搭建相关文件夹结构
  13. 网络编程(五) ———— 万字详解TCP协议
  14. 将自家的位置标注到地图上(51ditu.com)
  15. Flutter画中画自定义画中画
  16. HashMap线程安全性问题
  17. idea中执行“npm”命令,提示‘npm‘ 不是内部或外部命令,也不是可运行的程序
  18. few-shot learning个人总结
  19. Hadoop 之上的数据建模 - Data Vault 2.0
  20. 中国第一封email

热门文章

  1. C++重载一些需要注意的地方
  2. VBA自定义函数集锦[2]
  3. TEAM WORK 認清自己的角色
  4. react 组件与组件之间通讯
  5. python3 requests 库学习
  6. scrapy爬取京东
  7. Oracle的下载安装教程以及所出现的问题
  8. |Vijos|贪心|P1414 Dejected Birthday-盗窃
  9. 技术驱动还是产品驱动
  10. 案例展示快做好了(更新)