带条件的列表推导:处理带时间戳的数据
做得很好,您已经成功从 pandas DataFrame 中提取了需要的时间数据!现在通过添加一个条件来进一步细化要选择的条目。
在本练习中,您将使用列表推导式从带时间戳的 Twitter 数据中提取时间。您将为列表推导式添加条件表达式,使其只选择满足 entry[17:19] 等于 '19' 的时间。pandas 已以 pd 导入,文件 'tweets.csv' 已载入为 DataFrame df 供您使用。
本练习是课程的一部分
Python 工具箱
练习说明
- 从
df中提取'created_at'列,并将结果赋给tweet_time。 - 创建一个列表推导式,从
tweet_time的每一行中提取时间。每一行是表示时间戳的字符串,您需要访问字符串中的第 12 到第 19 个字符来提取时间。使用entry作为迭代变量,并将结果赋给tweet_clock_time。另外,添加条件表达式检查entry[17:19]是否等于'19'。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Extract the created_at column from df: tweet_time
tweet_time = ____
# Extract the clock time: tweet_clock_time
tweet_clock_time = [____ for ____ in ____ if ____ == ____]
# Print the extracted times
print(tweet_clock_time)