开始使用免费开始使用

行选择:loc[] 与 iloc[]

处理 DataFrame 的重要一环是从数据集中定位特定条目。定位行主要有两种方式:

  • 按某一列(特征)的特定取值。
  • 按行的索引(index)。本练习将聚焦第二种方式。

如果您之前用过 pandas,应该熟悉索引器 .loc.iloc,分别表示"按标签位置"和"按整数位置"。多数情况下,索引与行在 DataFrame 中的物理位置一致(例如索引为 13 的行是第 14 条记录)。

虽然这两个函数都能完成相同任务,但我们更关心哪一个在速度上更高效。

本练习是课程的一部分

使用 pandas 编写高效代码

查看课程

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Define the range of rows to select: row_nums
row_nums = range(0, 1000)

# Select the rows using .loc[] and row_nums and record the time before and after
loc_start_time = time.time()
rows = poker_hands.____[____]
loc_end_time = ___

# Print the time it took to select the rows using .loc[]
print("Time using .loc[]: {} sec".format(___ - ___))
编辑并运行代码