使用 .loc[] 进行子集选择
索引最强大的功能是 .loc[]:它是一种接受索引值的子集选择方法。当您只传入一个参数时,它会选取行的子集。
使用 .loc[] 的子集代码通常比常规的方括号子集更易读,这有助于降低代码维护成本。
已将 pandas 加载为 pd。temperatures 和 temperatures_ind 已提供;后者按 city 建立了索引。
本练习是课程的一部分
使用 pandas 进行数据处理
练习说明
- 创建名为
cities的列表,包含 "London" 和 "Paris"。 - 使用
[]子集选择,筛选temperatures中city列取值在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[____])