📌  相关文章
📜  如何在 Pandas 中根据日期范围对数据帧进行切片 - Python (1)

📅  最后修改于: 2023-12-03 15:38:22.446000             🧑  作者: Mango

如何在 Pandas 中根据日期范围对数据帧进行切片 - Python

在 Pandas 中,我们可以使用 Pandas 的日期和时间函数对时间序列数据进行切片。在本文中,我们将介绍如何使用 Pandas 中的数据帧来切片日期范围内的数据。

1. 导入 Pandas 模块

首先,我们需要导入 Pandas 模块。如果您尚未安装 Pandas,请使用以下命令将其安装:

!pip install pandas

接下来,我们使用以下命令导入 Pandas:

import pandas as pd
2. 创建数据帧

接下来,我们将创建一个包含日期列和数据列的示例数据帧。我们可以使用 Pandas 的 date_range 函数创建一个日期范围,并使用 random 模块创建随机数据:

import random

# Create a range of dates
dates = pd.date_range('2021-01-01', '2021-01-31')

# Create a dataframe with random data
df = pd.DataFrame({'date': dates, 'data': [random.randint(0, 100) for _ in range(len(dates))]})

# Print the dataframe
print(df.head())

这将创建一个包含日期和随机数据的数据帧。您应该看到以下输出:

        date  data
0 2021-01-01    55
1 2021-01-02    81
2 2021-01-03    65
3 2021-01-04    67
4 2021-01-05    83
3. 根据日期范围切片数据帧

现在我们已经创建了数据帧,我们可以使用 Pandas 日期和时间函数来对数据帧进行切片。

以下代码演示如何选择 2021 年 1 月份的数据:

# Select data from January 2021
january_data = df[(df['date'] >= '2021-01-01') & (df['date'] <= '2021-01-31')]

# Print the selected data
print(january_data.head())

这将选择 2021 年 1 月份的数据,并输出以下结果:

        date  data
0 2021-01-01    55
1 2021-01-02    81
2 2021-01-03    65
3 2021-01-04    67
4 2021-01-05    83

我们还可以使用 between 函数来选择日期范围内的数据。以下代码演示如何选择 2021 年 1 月 1 日到 1 月 15 日之间的数据:

# Select data in the date range of January 1st, 2021 to January 15th, 2021
january_data = df[df['date'].between('2021-01-01', '2021-01-15')]

# Print the selected data
print(january_data.head())

这将选择 2021 年 1 月 1 日到 1 月 15 日之间的数据,并输出以下结果:

        date  data
0 2021-01-01    55
1 2021-01-02    81
2 2021-01-03    65
3 2021-01-04    67
4 2021-01-05    83
结论

在本文中,我们介绍了如何使用 Pandas 中的数据帧来切片日期范围内的数据。我们可以使用日期和时间函数来选择指定日期范围内的数据,了解这些函数对于分析时间序列数据非常重要。