pandas loc、iloc、ix区别对比以及他们切片的区别

一开始自学Python的numpy、pandas时候,索引和切片把我都给弄晕了,特别是numpy的切片索引、布尔索引和花式索引,简直就是大乱斗。但是最近由于版本的问题,从之前的Python2.7改用Python3.6 了,在3.6中提供了loc和iloc两种索引方法,把ix这个方法给划分开来了,所以很有必要做个总结和对比。

1.1 loc、iloc、ix用途区别

loc:通过选取行(列)标签索引数据
iloc:通过选取行(列)位置编号索引数据
ix:既可以通过行(列)标签索引数据,也可以通过行(列)位置编号索引数据

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: df=pd.DataFrame(np.arange(20).reshape(4,5),index=['ind0','ind1','ind2','ind3'],columns=['col0','col1','col2','col3','col4'])

In [4]: df
Out[4]: 
      col0  col1  col2  col3  col4
ind0     0     1     2     3     4
ind1     5     6     7     8     9
ind2    10    11    12    13    14
ind3    15    16    17    18    19

上面这里构造了一个4*5的DataFrame数据,同时构造了行标签和列标签,下面就是各标签

In [5]: df.index
Out[5]: Index(['ind0', 'ind1', 'ind2', 'ind3'], dtype='object')

In [6]: df.columns
Out[6]: Index(['col0', 'col1', 'col2', 'col3', 'col4'], dtype='object')

下面就是所谓的位置编号,其实就是位置索引,跟列表数据同理

In [7]: np.arange(len(df.index))
Out[7]: array([0, 1, 2, 3])

In [8]: np.arange(len(df.columns))
Out[8]: array([0, 1, 2, 3, 4])

1.1 loc

loc只能通过选取行标签索引数据

In [8]: df.loc['ind0']
Out[8]: 
col0    0
col1    1
col2    2
col3    3
col4    4
Name: ind0, dtype: int32

In [9]: df.loc[0]
Traceback (most recent call last):
  ##报错的详细信息,我就不占篇幅展示了
TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <class 'int'>

如果用到了行(列)的位置索引就会报错

1.2 iloc

iloc只能通过选取行位置编号索引数据

In [10]: df.iloc[0]
Out[10]: 
col0    0
col1    1
col2    2
col3    3
col4    4
Name: ind0, dtype: int32

In [11]: df.iloc['ind0']
Traceback (most recent call last):
##报错的详细信息,我就不占篇幅展示了
TypeError: cannot do positional indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [ind0] of <class 'str'>

同样的,如果使用了行(列)标签就会报错

1.3 ix

ix 既可以通过行标签索引数据,也可以通过行位置编号索引数据,也是我的最爱

In [12]: df.ix[0]
__main__:1: DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
Out[12]: 
col0    0
col1    1
col2    2
col3    3
col4    4
Name: ind0, dtype: int32

In [13]: df.ix['ind0']
Out[13]: 
col0    0
col1    1
col2    2
col3    3
col4    4
Name: ind0, dtype: int32

想用哪个就用哪个,但是用到ix的时候提示已被弃用,但还是我的最爱。

1.4 loc、iloc、ix对于列的索引

loc、iloc、ix对于列的索引跟对行的索引是一样的,loc只能通过选取列标签索引数据,iloc只能通过选取列位置编号索引数据,ix 既可以通过行标签索引数据,也可以通过行位置编号索引数据,还可以两者混用,爱无止境。

In [14]: df.loc['ind0','col0']
Out[14]: 0

In [15]: df.loc['ind0',0]
Traceback (most recent call last):
##报错的详细信息,我就不占篇幅展示了
TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <class 'int'>

In [16]: 

In [16]: df.iloc[0,0]
Out[16]: 0

In [17]: df.iloc[0,'col0']
Traceback (most recent call last):
##报错的详细信息,我就不占篇幅展示了
ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types

In [18]: 

In [18]: df.ix[0,0]
Out[18]: 0

In [19]: df.ix[0,'col0']
Out[19]: 0

2. loc、iloc、ix使用切片的区别

loc、iloc、ix对于切片的索引数据就两种情况,按照标签切片索引和按照位置编号切片索引

In [20]: df.loc['ind0':'ind3']
Out[20]: 
      col0  col1  col2  col3  col4
ind0     0     1     2     3     4
ind1     5     6     7     8     9
ind2    10    11    12    13    14
ind3    15    16    17    18    19

In [21]: df.iloc[0:3]
Out[21]: 
      col0  col1  col2  col3  col4
ind0     0     1     2     3     4
ind1     5     6     7     8     9
ind2    10    11    12    13    14

区别不在于用哪种方法,而是通过标签索引将会将切片末端包含进去,通过位置编号索引不会讲切片末端包含进去。同样的都是第一行到第四行,通过loc就会把1,2,3,4行都提取出来,通过iloc就只能把1,2,3行提取出来。ix方法也是一样,知识方法不同而已。

In [23]: df.ix['ind0':'ind3']
Out[23]: 
      col0  col1  col2  col3  col4
ind0     0     1     2     3     4
ind1     5     6     7     8     9
ind2    10    11    12    13    14
ind3    15    16    17    18    19

In [24]: df.ix[0:3]
Out[24]: 
      col0  col1  col2  col3  col4
ind0     0     1     2     3     4
ind1     5     6     7     8     9
ind2    10    11    12    13    14

对于列的切片跟行的一样。

这里讨论了基本的索引和切片,如果有用词不当的地方请提出来,我将积极改正,或者有其他有关花式索引、布尔索引的问题也可以大家一起讨论讨论!

  • 17
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
回答: 在使用pandas对指定列行进行切片时,可以使用以下方法。首先,可以使用读取整个文件后进行切片处理的方法。通过使用`df.iloc`来取出特定行或列。例如,使用`df.iloc\[0\]`可以获取第一行的数据,使用`df.iloc\[:3\]`可以获取前三行的数据,使用`df.iloc\[:, 0\]`可以获取第一列的数据,使用`df.iloc\[:, :2\]`可以获取前两列的数据。此外,还可以使用`df\[3:10\]`来获取第四行到第十行的数据,使用`df\["列的名字"\]`来直接查看某一列的值。这些操作类似于对列表进行切片操作。\[1\] 另外,还可以使用不读取整个文件,而是读取特定行和列的方法。当遇到文件太大时,可以直接读取所需的指定行和列。使用`pd.read_csv`函数的`nrows`参数可以指定读取的行数,例如`pd.read_csv("路径\文件名称", nrows=15)`可以只读取前十五行。使用`pd.read_csv`函数的`skiprows`参数可以指定需要忽略的行数,例如`pd.read_csv("路径\文件名称", skiprows=9, nrows=5)`可以忽略前九行,然后读取接下来的五行。对于列的选择,可以使用`usecols`参数来指定要读取的列,例如`pd.read_csv("1217_1out.csv", usecols=\[0\])`可以只读取第一列的数据。\[1\] 需要注意的是,使用`.loc`、`.iloc`、`.ix`等方法时,只提供一个参数时,进行的是行选择。而使用`.loc`、`.at`方法选择列时,只能使用列名,不能使用位置。而使用`.iloc`、`.iat`方法选择列时,只能使用位置,不能使用列名。另外,使用`df\[\]`只能进行行选择或列选择,不能同时进行列选择,列选择只能使用列名。\[2\] 最后,需要注意行列索引以及默认的索引值。在pandas中,数据存储本身可能有起始列,但是pandas读取后会默认给一个递增的索引值。通过使用`.loc`方法可以通过值来进行切片操作。\[3\] #### 引用[.reference_title] - *1* [pandas读取指定行/列的几种操作](https://blog.csdn.net/bianxia123456/article/details/111396760)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [python pandas dataframe 行列选择,切片操作](https://blog.csdn.net/LY_ysys629/article/details/55224284)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Pandas提取指定行列](https://blog.csdn.net/weixin_42670810/article/details/109685030)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值