Pandas实战100例 | 案例 51: 日期时间过滤

案例 51: 日期时间过滤

知识点讲解

当你的 DataFrame 包含 datetime 类型的列时,你可以基于日期时间条件过滤数据。这在处理时间序列数据时特别有用。

  • 日期时间过滤: 使用布尔索引,可以根据日期时间条件过滤数据。
示例代码
# 准备数据和示例代码的运行结果,用于案例 51

# 示例数据
data_datetime_filtering = {
    'Date': pd.date_range(start='2023-01-01', periods=5, freq='D'),
    'Values': [10, 20, 30, 40, 50]
}
df_datetime_filtering = pd.DataFrame(data_datetime_filtering)

# 日期时间过滤
filtered_dates = df_datetime_filtering[df_datetime_filtering['Date'] >= '2023-01-03']

df_datetime_filtering, filtered_dates


在这个示例中,我们选择了日期大于或等于 ‘2023-01-03’ 的所有行。

示例代码运行结果

原始 DataFrame (df_datetime_filtering):

        Date  Values
0 2023-01-01      10
1 2023-01-02      20
2 2023-01-03      30
3 2023-01-04      40
4 2023-01-05      50

日期时间过滤后的数据 (filtered_dates):

        Date  Values
2 2023-01-03      30
3 2023-01-04      40
4 2023-01-05      50

这个结果展示了如何基于日期时间条件过滤数据。此类过滤对于时间序列分析和数据预处理至关重要。

你可能感兴趣的:(Pandas实战100例,pandas,人工智能)