The loc and iloc属性是 Pandas 库的一部分,允许根据某些标准从 DataFrame 中选择数据。
本教程将讨论这两种属性之间的主要区别,以及如何确保您使用适合您特定需求的属性。
下表总结了这两个属性之间的差异:
Property |
loc |
iloc |
Indexing type |
Label-based |
Integer-based |
Data selected |
By the value of the index |
By the position in the DataFrame |
Format of arguments |
Single label, list of labels, slice object with labels, boolean array |
Single integer, list of integers, slice objects, boolean array |
Includes final value in range |
Yes |
No |
Handles boolean indexing |
Directly |
Indirectly, using a boolean array |
Can result in confusion with integer index |
Yes, if index also contains integers |
No |
Performance |
– |
Slightly faster |
现在,让我们深入了解细节。首先,让我们创建一个数据框作为样本:
import pandas as pd
data = pd.DataFrame({
'Age': [26, 27, 28, 29, 30],
'Height': [165, 168, 170, 173, 175],
'Weight': [55, 58, 60, 63, 65]},
index=['Emily', 'Ava', 'Charlotte', 'Sophia', 'Olivia']
)
print(data)
Output
Age Height Weight
Emily 26 165 55
Ava 27 168 58
Charlotte 28 170 60
Sophia 29 173 63
Olivia 30 175 65
这是我们将要处理的 DataFrame。正如您所看到的,它保存了五个人的数据,并包含他们的年龄、身高和体重。
使用 loc 和 iloc 选择行
loc 和 iloc 都可用于行选择,但它们的操作方式略有不同。
# Selecting a range of rows with loc
print(data.loc['Emily':'Charlotte'])
Output:
Age Height Weight
Emily 26 165 55
Ava 27 168 58
Charlotte 28 170 60
使用 loc,我们可以选择一系列行,重要的是,该范围包括开始索引和停止索引。上面的代码选择从“Emily”到“Charlotte”(含)的三行。
# Selecting a range of rows with iloc
print(data.iloc[0:2])
Output:
Age Height Weight
Emily 26 165 55
Ava 27 168 58
当我们使用 iloc 选择行时,我们需要记住,与 loc 不同,范围包含起始索引,不包含终止索引。本质上,它与典型的 Python 索引是一致的。
使用 loc 和 iloc 进行切片
让我们探讨一下 loc 和 iloc 在数据帧切片方面有何不同
# Slicing with loc
print(data.loc['Emily':'Sophia', 'Age':'Height'])
Output:
Age Height
Emily 26 165
Ava 27 168
Charlotte 28 170
Sophia 29 173
使用 loc,我们可以通过指定范围来对行和列进行切片。
请注意,此处的范围包括停止索引。
# Slicing with iloc
print(data.iloc[0:4, 0:2])
Output:
Age Height
Emily 26 165
Ava 27 168
Charlotte 28 170
Sophia 29 173
与 loc 不同,这里的停止索引是独占的。
布尔索引
Pandas 中的布尔索引通过选择 DataFrame 中条件为 true 的行来工作。
# Boolean indexing with loc
print(data.loc[data['Age'] > 27])
Output:
Age Height Weight
Charlotte 28 170 60
Sophia 29 173 63
Olivia 30 175 65
在此示例中,我们使用 loc 来选择“Age”大于 27 的所有行。
大括号内的条件是布尔条件,用于检查“Age”是否大于 27。
然后 loc 属性仅返回此条件为 True 的行。
然而,对于国际劳工组织,情况有所不同。
# Attempting boolean indexing with iloc
# Uncomment the below lines to run the code
#print(data.iloc[data['Age'] > 27])
如果您尝试使用 iloc 进行布尔索引,如上面注释的代码所示,您将遇到错误。
这凸显了 loc 和 iloc 之间的一个重要区别 - iloc 不直接支持布尔索引。
相反,您需要获取布尔索引,然后使用它进行数据选择。
# Boolean indexing workaround with iloc
boolean_index = data['Age'] > 27
print(data.iloc[boolean_index.values])
Output:
Age Height Weight
Charlotte 28 170 60
Sophia 29 173 63
Olivia 30 175 65
在上面的代码中,我们首先获得一个布尔索引,其中“Age”大于27。
然后将该索引传递给 iloc 方法以获取所需的行。
性能比较
让我们通过一个简单的基准测试来看看 loc 和 iloc 的性能。
import timeit
import pandas as pd
import numpy as np
# Create a large DataFrame
large_data = pd.DataFrame(np.random.rand(10000, 10000))
# Time loc
loc_start_time = timeit.default_timer()
large_data.loc[0, 0]
loc_end_time = timeit.default_timer()
loc_time = loc_end_time - loc_start_time
# Time iloc
iloc_start_time = timeit.default_timer()
large_data.iloc[0, 0]
iloc_end_time = timeit.default_timer()
iloc_time = iloc_end_time - iloc_start_time
print("Time taken for loc: {:.6f} seconds".format(loc_time))
print("Time taken for iloc: {:.6f} seconds".format(iloc_time))
Output:
Time taken for loc: 0.005681 seconds
Time taken for iloc: 0.000095 seconds
请注意,实际处理时间将根据环境、DataFrame 的大小以及正在执行的任务而有所不同。
从上面的例子中,我们可以得出结论,iloc 的执行速度比 loc 稍快。
结论是,如果您知道您将根据整数索引引用行/列,并且速度是优先考虑的,那么 iloc 可能是您的选择。
但是,一般建议是更多地根据您的索引需求是基于标签 (loc) 还是基于整数 (iloc) 进行选择,而不是基于哪个更快。
何时使用 loc 与 iloc
虽然它们提供非常相似的功能,但存在根本差异,使它们适合不同的任务。
在以下情况下使用 loc:
- 您想要基于标签的索引。 loc 旨在处理这种情况。
- 数据集有一个字符串索引。
- 您正在使用布尔索引。 loc 可以接受布尔数组来直接索引。
在以下情况下使用 iloc:
- 您的 DataFrame 有一个数字索引。虽然 loc 可以使用数字标签,但如果标签也是整数,有时会导致混乱。
- 您依赖于数据帧中项目的位置。
- 您需要稍微提高速度。在计算测试中,iloc 的性能略优于 loc。