1. 主要用法
在Pandas里面,主要由3种方法来选择数据。
- 通过
行
来选择(.iloc) - 通过
label
和条件表达
来选择数据(.loc)
2. 使用iloc
来选择数据
iloc
意味着integer-location based indexing / selecting
by position.
iloc 索引语法如下
data.iloc[<row selection>,<column selection>]
在Pandas里面,iloc
定义为:利用数字来选择行和列。
在iloc
里面,一共有两种语法:
- row selector
- column selector
# single selections using iloc and DataFrame
# Rows:
data.iloc[0] # first row of data frame
data.iloc[1] # second row of data frame
data.iloc[-1] # last row of data frame
# Columns:
data.iloc[:,0] # first column of data frame
data.iloc[:,1] # second column of data frame
如果我们需要选择多列和多行,我们可以使用.iloc indexer
。
# Multiple row and column selections using iloc and DataFrame
data.iloc[0:5] # first 5 rows of data frame
data.iloc[:,0:2] # first 2 columns of data frame with all rows
data.iloc[[0,3,6,24],[0,5,6]] # 1st, 4th, 7th, 25th row;
# 1st 6th 7th columns
data.iloc[0:5,5:8] # first 5 rows
# 5th, 6th, 7th columns of data frame
在使用iloc
时候,有2点需要注意一下:
- 当只选择一行的时候,
.iloc
返回的是一个Pandas Series;如果选择了多行,返回的是一个Pandas DataFrame。因为,如果我们只选择一行,但是我们又希望输出是一个DataFrame,我们可以用[]
将其括起来
具体可以参考下面的图片:
在我们使用.loc
或者.iloc
的时候,我们可以通过输入是一个list或者一个单个的值,来控制输出的数据类型。
- 当我们当使用这种选择方式的时候,比如
[1:5]
,我们选择的行和列会从第1个选择到倒数第二个,比如[1:5]
会是1,2,3,4
。如果是[x,y]
,就会是从x
到y -1
。
3. 使用loc
来选择数据
Pandas 的loc
可以在两种场景下使用:
- 通过 label / index 选择行
- 使用 boolean / conditional lookup 查找行
3.1 基于label / index, 使用.loc
3.2 基于 Boolean / Logical,使用.loc
参考: