在Pandas中使用iloc, loc和ix来选择行和列

这篇博客介绍了在Pandas中选择数据的方法,主要关注.iloc, .loc和.ix。.iloc基于位置选择数据,.loc则依据标签或布尔条件。.iloc使用数字索引,.loc支持标签和逻辑筛选。.ix则结合了两者,但已弃用。博客详细阐述了每种方法的语法和注意事项,并提供了使用示例。" 150912,3196,GDI+创建Image对象:Bitmap构造方法详解,"['gdi+', 'image处理', 'vb.net', 'c#编程', 'windows应用开发']

1. 主要用法

在Pandas里面,主要由3种方法来选择数据。

  1. 通过来选择(.iloc)
  2. 通过label条件表达来选择数据(.loc)

2. 使用iloc来选择数据

iloc意味着integer-location based indexing / selecting by position.

iloc 索引语法如下

data.iloc[<row selection>,<column selection>]

在Pandas里面,iloc定义为:利用数字来选择行和列。

iloc里面,一共有两种语法:

  1. row selector
  2. 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点需要注意一下:

  1. 当只选择一行的时候,.iloc返回的是一个Pandas Series;如果选择了多行,返回的是一个Pandas DataFrame。因为,如果我们只选择一行,但是我们又希望输出是一个DataFrame,我们可以用[]将其括起来

具体可以参考下面的图片:
在这里插入图片描述
在我们使用.loc或者.iloc的时候,我们可以通过输入是一个list或者一个单个的值,来控制输出的数据类型。

  1. 当我们当使用这种选择方式的时候,比如[1:5],我们选择的行和列会从第1个选择到倒数第二个,比如[1:5]会是1,2,3,4。如果是[x,y] ,就会是从xy -1

3. 使用loc来选择数据

Pandas 的loc可以在两种场景下使用:

  1. 通过 label / index 选择行
  2. 使用 boolean / conditional lookup 查找行

3.1 基于label / index, 使用.loc

3.2 基于 Boolean / Logical,使用.loc

参考:

  1. https://www.shanelynn.ie/select-pandas-dataframe-rows-and-columns-using-iloc-loc-and-ix/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值