时间序列切片
切片对时间序列尤其有用,因为我们常常需要按日期范围筛选数据。请将 date 列添加到索引中,然后使用 .loc[] 来完成子集选择。要点是日期要使用 ISO 8601 格式,即年-月-日用 "yyyy-mm-dd",年-月用 "yyyy-mm",年份用 "yyyy"。
回顾第 1 章,您可以使用逻辑运算符(如 &)组合多个布尔条件。若要在一行代码中完成,需要在每个条件外加上括号 ()。
已导入 pandas 为 pd,并提供了无索引的 temperatures。
本练习是课程的一部分
使用 pandas 进行数据处理
练习说明
- 使用布尔条件(不要用
.isin()或.loc[]),并使用完整日期"yyyy-mm-dd",对temperatures进行子集选择,筛选date列在 2010 和 2011 年的行,并打印结果。 - 将
temperatures的索引设为date列并排序。 - 使用
.loc[]对temperatures_ind进行子集选择,筛选 2010 和 2011 年的行。 - 使用
.loc[]对temperatures_ind进行子集选择,筛选从 August 2010 到 February 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(____)