Pandas 日期时间

2024 年 8 月 29 日 | 阅读 3 分钟

Pandas 可以提供在所有领域处理时间序列数据的功能。 它还通过使用 NumPy datetime64 和 timedelta64 dtypes,整合了来自其他 Python 库(如 scikits.timeseries)的大量功能。 它提供了用于操作时间序列数据的新功能。 在 Pandas Datetime 中执行的操作可以列出如下

  1. DatetimeIndex
  2. 日期范围生成
  3. 本地化和转换
  4. 时区处理
  5. 时间序列操作

时间序列工具对于数据科学应用程序最有用,并且与其他在 Python 中使用的软件包相关。

示例 1:DatetimeIndex

以下代码生成一个以“5/4/2013”开头的八个日期序列,频率为一秒。

编码

输出

DatetimeIndex(['2013-05-04 00:00:00', '2013-05-04 00:00:01',
               '2013-05-04 00:00:02', '2013-05-04 00:00:03',
               '2013-05-04 00:00:04', '2013-05-04 00:00:05',
               '2013-05-04 00:00:06', '2013-05-04 00:00:07'],
              dtype='datetime64[ns]', freq='S')

示例 2:转换

以下代码使用 Pandas 中的 pd.to_datetime() 函数,将 DataFrame 中单独的年、月和日列转换为单个日期时间格式。

编码

输出

0   2014-05-20
1   2012-07-17
dtype: datetime64[ns]

示例 3:范围生成

以下代码生成一个以“2017-06-04”开头的五个日期序列,频率为一秒。

编码

Example3

输出

DatetimeIndex(['2017-06-04 00:00:00', 
               '2017-06-04 00:00:01',
               '2017-06-04 00:00:02',
               '2017-06-04 00:00:03',
               '2017-06-04 00:00:04'],
               dtype='datetime64[ns]', freq='S')

示例 4:本地化

下面的 python datetime 代码使用 Pandas 中的 tz_localize() 函数,将由变量“dmy”表示的日期时间序列的时区本地化为 UTC。

编码

输出

DatetimeIndex(['2017-06-04 00:00:00+00:00', '2017-06-04 00:00:01+00:00',
               '2017-06-04 00:00:02+00:00', 
               '2017-06-04 00:00:03+00:00',
               '2017-06-04 00:00:04+00:00'],
              dtype='datetime64[ns, UTC]', freq='S')

示例 5:时间序列操作

编写以下代码是为了执行时间序列操作,如滚动平均值。

编码

输出

DataFrame:
            Value
2022-01-01     10
2022-01-02     15
2022-01-03      8
2022-01-04     12
2022-01-05      9

Rolling Mean:
2022-01-01          NaN
2022-01-02          NaN
2022-01-03     11.000000
2022-01-04     11.666667
2022-01-05      9.666667
Freq: D, Name: Value, dtype: float64

结论

Pandas 库为在 Python 中处理日期时间信息提供了强大的实用性。 它提供了不同的元素来有效地处理、控制和分解日期和时间。


下一个主题Pandas 时间偏移