开始使用免费开始使用

时间序列切片

切片对时间序列尤其有用,因为我们常常需要按日期范围筛选数据。请将 date 列添加到索引中,然后使用 .loc[] 来完成子集选择。要点是日期要使用 ISO 8601 格式,即年-月-日用 "yyyy-mm-dd",年-月用 "yyyy-mm",年份用 "yyyy"

回顾第 1 章,您可以使用逻辑运算符(如 &)组合多个布尔条件。若要在一行代码中完成,需要在每个条件外加上括号 ()

已导入 pandaspd,并提供了无索引的 temperatures

本练习是课程的一部分

使用 pandas 进行数据处理

查看课程

练习说明

  • 使用布尔条件(不要用 .isin().loc[]),并使用完整日期 "yyyy-mm-dd",对 temperatures 进行子集选择,筛选 date 列在 2010 和 2011 年的行,并打印结果。
  • temperatures 的索引设为 date 列并排序。
  • 使用 .loc[]temperatures_ind 进行子集选择,筛选 2010 和 2011 年的行。
  • 使用 .loc[]temperatures_ind 进行子集选择,筛选从 August 2010February 2011 的行。

交互式实操练习

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

# Use Boolean conditions to subset temperatures for rows in 2010 and 2011
temperatures_bool = ____[(____ >= ____) & (____ <= ____)]
print(temperatures_bool)

# Set date as the index and sort the index
temperatures_ind = temperatures.____.____

# Use .loc[] to subset temperatures_ind for rows in 2010 and 2011
print(____)

# Use .loc[] to subset temperatures_ind for rows from Aug 2010 to Feb 2011
print(____)
编辑并运行代码