开始使用免费开始使用

使用 .loc[] 进行子集选择

索引最强大的功能是 .loc[]:它是一种接受索引值的子集选择方法。当您只传入一个参数时,它会选取行的子集。

使用 .loc[] 的子集代码通常比常规的方括号子集更易读,这有助于降低代码维护成本。

已将 pandas 加载为 pdtemperaturestemperatures_ind 已提供;后者按 city 建立了索引。

本练习是课程的一部分

使用 pandas 进行数据处理

查看课程

练习说明

  • 创建名为 cities 的列表,包含 "London""Paris"
  • 使用 [] 子集选择,筛选 temperaturescity 列取值在 cities 列表中的行。
  • 使用 .loc[] 子集选择,筛选 temperatures_ind 中城市在 cities 列表中的行。

交互式实操练习

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

# Make a list of cities to subset on
cities = ["____", "____"]

# Subset temperatures using square brackets
print(temperatures[____])

# Subset temperatures_ind using .loc[]
print(temperatures_ind.loc[____])
编辑并运行代码