Pandas使用 `iloc` 和 `loc` 常见用法汇总


df.ilocdf.loc 是 Pandas 中用于选择数据的两个重要函数。 df.iloc 基于整数位置索引,而 df.loc 基于标签(标签索引)选择数据。以下是它们的常见用法汇总:

df.iloc 常见用法

df.iloc 是基于整数位置的选择方法,用于按位置索引选择数据。

1. 获取特定行
  • 获取第一行

    first_row = df.iloc[0]
    

    获取 DataFrame 的第一行。

  • 获取最后一行

    last_row = df.iloc[-1]
    

    获取 DataFrame 的最后一行。

2. 获取特定列
  • 获取第一列

    first_column = df.iloc[:, 0]
    

    获取 DataFrame 的第一列。

  • 获取最后一列

    last_column = df.iloc[:, -1]
    

    获取 DataFrame 的最后一列。

3. 获取特定的行和列
  • 获取第一行和第一列的值

    value = df.iloc[0, 0]
    

    获取 DataFrame 的第一行第一列的值。

  • 获取最后一行和最后一列的值

    value = df.iloc[-1, -1]
    

    获取 DataFrame 的最后一行最后一列的值。

4. 获取行切片
  • 获取前五行

    first_five_rows = df.iloc[:5]
    

    获取 DataFrame 的前五行。

  • 获取最后三行

    last_three_rows = df.iloc[-3:]
    

    获取 DataFrame 的最后三行。

5. 获取列切片
  • 获取前两列

    first_two_columns = df.iloc[:, :2]
    

    获取 DataFrame 的前两列。

  • 获取从第二列到第四列

    middle_columns = df.iloc[:, 1:4]
    

    获取 DataFrame 的第二列到第四列(不包括第四列)。

6. 获取特定的行和列切片
  • 获取前两行和前两列

    first_two_rows_and_columns = df.iloc[:2, :2]
    

    获取 DataFrame 的前两行和前两列。

  • 获取最后两行和最后两列

    last_two_rows_and_columns = df.iloc[-2:, -2:]
    

    获取 DataFrame 的最后两行和最后两列。

df.loc 常见用法

df.loc 是基于标签(标签索引)的选择方法,用于按标签选择数据。

1. 获取特定行
  • 获取特定标签行
    row = df.loc['row_label']
    
    获取 DataFrame 中标签为 'row_label' 的行。
2. 获取特定列
  • 获取特定标签列
    column = df.loc[:, 'column_label']
    
    获取 DataFrame 中标签为 'column_label' 的列。
3. 获取特定的行和列
  • 获取特定标签的行和列的值
    value = df.loc['row_label', 'column_label']
    
    获取 DataFrame 中标签为 'row_label' 的行和 'column_label' 的列的值。
4. 获取行切片
  • 获取标签范围内的行
    rows = df.loc['start_label':'end_label']
    
    获取 DataFrame 中从 'start_label''end_label' 的行。
5. 获取列切片
  • 获取标签范围内的列
    columns = df.loc[:, 'start_column':'end_column']
    
    获取 DataFrame 中从 'start_column''end_column' 的列。
6. 获取特定的行和列切片
  • 获取特定标签范围内的行和列
    rows_and_columns = df.loc['start_label':'end_label', 'start_column':'end_column']
    
    获取 DataFrame 中从 'start_label''end_label' 的行和从 'start_column''end_column' 的列。

示例代码

import pandas as pd

# 创建一个示例 DataFrame
data = {'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50], 'C': [100, 200, 300, 400, 500]}
df = pd.DataFrame(data, index=['a', 'b', 'c', 'd', 'e'])

# iloc 示例
first_row = df.iloc[0]
last_row = df.iloc[-1]
first_column = df.iloc[:, 0]
last_column = df.iloc[:, -1]
value = df.iloc[0, 0]
first_five_rows = df.iloc[:5]
last_three_rows = df.iloc[-3:]
first_two_columns = df.iloc[:, :2]
middle_columns = df.iloc[:, 1:3]
first_two_rows_and_columns = df.iloc[:2, :2]
last_two_rows_and_columns = df.iloc[-2:, -2:]

# loc 示例
row = df.loc['a']
column = df.loc[:, 'A']
value = df.loc['a', 'A']
rows = df.loc['a':'c']
columns = df.loc[:, 'A':'B']
rows_and_columns = df.loc['a':'c', 'A':'B']

print("First row using iloc:")
print(first_row)
print("\nLast row using iloc:")
print(last_row)
print("\nFirst column using iloc:")
print(first_column)
print("\nLast column using iloc:")
print(last_column)
print("\nValue at first row and first column using iloc:")
print(value)
print("\nFirst five rows using iloc:")
print(first_five_rows)
print("\nLast three rows using iloc:")
print(last_three_rows)
print("\nFirst two columns using iloc:")
print(first_two_columns)
print("\nMiddle columns using iloc:")
print(middle_columns)
print("\nFirst two rows and columns using iloc:")
print(first_two_rows_and_columns)
print("\nLast two rows and columns using iloc:")
print(last_two_rows_and_columns)

print("\nRow 'a' using loc:")
print(row)
print("\nColumn 'A' using loc:")
print(column)
print("\nValue at row 'a' and column 'A' using loc:")
print(value)
print("\nRows 'a' to 'c' using loc:")
print(rows)
print("\nColumns 'A' to 'B' using loc:")
print(columns)
print("\nRows 'a' to 'c' and columns 'A' to 'B' using loc:")
print(rows_and_columns)

这个代码示例展示了如何使用 ilocloc 进行各种常见的数据选择操作。

<think>嗯,用户问的是pandas中的ilocloc的区别,这应该是关于数据处理的。我需要先回忆一下这两个方法的用法。首先,loc是基于标签的索引,而iloc是基于整数位置的索引。对吧? 记得loc使用DataFrame的index或者columns的标签来选择数据,而iloc则是用位置,比如第几行、第几列,不管标签是什么。比如,如果DataFrame的索引是字母a、b、c,那么loc['a']就能选到第一行,而iloc[0]也是第一行,不管索引标签是什么。 不过用户可能不太清楚具体怎么用,得举例子说明。比如,当使用loc的时候,可以传入行标签列标签,甚至切片,比如df.loc['a':'c', 'col1':'col3']。而iloc的话,参数是行列的位置,比如df.iloc[0:3, 1:4],这里要注意左闭右开的问题,iloc的切片Python列表一样,不包含结束位置。 还有布尔索引的问题,loc可以接受布尔数组,比如df.loc[df['age'] > 30],这样筛选出符合条件的行。但iloc不能直接用布尔数组,可能需要先生成位置索引再传入。 另外,用户可能会混淆两者的输入类型,比如loc可以用整数作为标签,如果索引本身就是整数的话,这时候用lociloc的结果可能不同。比如,如果索引是5、6、7,那么loc[5:7]会包括5、6、7三个行,而iloc[5:7]则是第5第6行(假设从0开始的话可能越界,这里可能例子需要调整)。 再想想有没有其他需要注意的地方。比如loc可以同时选择行列,而iloc也一样,但是参数的位置不同。还有,当使用单个元素的时候,loc返回的是Series,而用切片的话返回DataFrame。或者当用逗号分隔行列选择时,比如df.loc[行选择, 列选择]。 可能用户需要具体的代码示例来对比两者的区别。比如创建一个简单的DataFrame,然后分别用lociloc操作,显示不同的结果。这样用户更容易理解。 总结一下,loc是基于标签的,包括结尾;iloc基于位置,左闭右开。同时,loc可以接受布尔数组,而iloc需要位置索引。应用场景上,当需要按标签选择数据时用loc,按位置则用iloc。要提醒用户注意索引的类型,避免混淆。 最后检查有没有错误的地方,比如iloc是否真的不能接受布尔数组?好像是的,iloc的参数应该是整数或整数列表、切片等,不能直接用布尔数组,必须通过np.where或者类似的转换成位置索引。这点需要确认,避免误导用户。</think>在Pandas中,`iloc``loc`是用于数据索引的核心方法,它们的主要区别如下: --- ### **1. `loc`:基于标签的索引** - **作用** 通过行/列的**标签(label)**或**布尔数组**选择数据。 - **特点** - 标签可以是索引名(如字符串`"a"`或整数`5`)或条件表达式(如`df["age"] > 30`)。 - 切片范围**包含结束值**(例如`"a":"c"`会选中`a`、`b`、`c`)。 - **语法** ```python df.loc[行选择, 列选择] ``` - **示例** ```python import pandas as pd df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=["a", "b", "c"]) # 选择标签为"a"的行 df.loc["a"] # 输出:A=1, B=4 # 选择行标签为"a"到"c",列标签为"A" df.loc["a":"c", "A"] # 输出:a=1, b=2, c=3 # 通过布尔条件筛选 df.loc[df["A"] > 1] # 输出:行bc ``` --- ### **2. `iloc`:基于位置的索引** - **作用** 通过行/列的**整数位置(从0开始)**选择数据。 - **特点** - 位置是整数(如`0`表示第一行)。 - 切片范围**不包含结束值**(例如`0:3`选中第0、1、2行)。 - **语法** ```python df.iloc[行位置, 列位置] ``` - **示例** ```python # 选择第0行(第一行) df.iloc[0] # 输出:A=1, B=4 # 选择第0到第1行(不包含2),第1列(B列) df.iloc[0:2, 1] # 输出:4, 5 # 通过位置列表选择 df.iloc[[0, 2]] # 输出:行ac ``` --- ### **3. 关键区别总结** | 特性 | `loc` | `iloc` | |--------------|--------------------------------|---------------------------------| | **索引类型** | 标签(字符串/整数) | 整数位置(从0开始) | | **切片范围** | 包含结束值(如`"a":"c"`全选) | 不包含结束值(如`0:2`选01) | | **适用场景** | 按标签筛选数据 | 按绝对位置筛选数据 | --- ### **4. 常见误区** 1. **混淆索引类型** - 如果索引是整数,`loc[0]``iloc[0]`可能指向不同行(例如索引被重置为`5,6,7`时)。 2. **混合使用标签位置** - `loc`只能用标签,`iloc`只能用整数位置,不可混用。 --- ### **5. 如何选择?** - 需要按**列名、行名或条件表达式**筛选时 → **用`loc`**。 - 需要按**绝对位置**(如第1行、第2列)筛选时 → **用`iloc`**。 通过理解两者的差异,可以更高效地操作Pandas DataFrame!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今晚务必早点睡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值