python - Pandas - 从索引中提取月份和年份

我有一个以日期时间为索引的数据框。如何从索引中提取年份和月份?下面是我的数据框。

            1. open   2. high    3. low  4. close   5. volume
date                                                         
2019-01-07   101.64  103.2681  100.9800    102.06  35656136.0
2019-01-08   103.04  103.9700  101.7134    102.80  31294058.0

显然 df["index"].dt.monthdf["date"].dt.month 不起作用。

最佳答案

您可以使用下面的示例,但是您可以从Docs pandas.DatetimeIndex中获得详细用法

示例数据框:

>>> df
                              name  age favorite_color  grade  birth_date
Willard Morris      Willard Morris   20           blue     88  01-02-1996
Al Jennings            Al Jennings   19            red     92  08-05-1997
Omar Mullins          Omar Mullins   22         yellow     95  04-28-1996
Spencer McDaniel  Spencer McDaniel   21          green     70  12-16-1995

1) 提取年份:

>>> df['year'] = pd.DatetimeIndex(df['birth_date']).year
>>> df.head()
                              name  age favorite_color  grade  birth_date  year
Willard Morris      Willard Morris   20           blue     88  01-02-1996  1996
Al Jennings            Al Jennings   19            red     92  08-05-1997  1997
Omar Mullins          Omar Mullins   22         yellow     95  04-28-1996  1996
Spencer McDaniel  Spencer McDaniel   21          green     70  12-16-1995  1995

2) 提取月份:

>>> df['month'] = pd.DatetimeIndex(df['birth_date']).month
>>> df.head()
                              name  age favorite_color  grade  birth_date  year  month
Willard Morris      Willard Morris   20           blue     88  01-02-1996  1996      1
Al Jennings            Al Jennings   19            red     92  08-05-1997  1997      8
Omar Mullins          Omar Mullins   22         yellow     95  04-28-1996  1996      4
Spencer McDaniel  Spencer McDaniel   21          green     70  12-16-1995  1995     12

3)提取year_with_month:

>>> df['month_year'] = pd.to_datetime(df['birth_date']).dt.to_period('M')
>>> df
                              name  age favorite_color  grade  birth_date  year  month month_year
Willard Morris      Willard Morris   20           blue     88  01-02-1996  1996      1    1996-01
Al Jennings            Al Jennings   19            red     92  08-05-1997  1997      8    1997-08
Omar Mullins          Omar Mullins   22         yellow     95  04-28-1996  1996      4    1996-04
Spencer McDaniel  Spencer McDaniel   21          green     70  12-16-1995  1995     12    1995-12

https://stackoverflow.com/questions/54110673/

相关文章:

node.js - 如何将字符串作为 gzip Nodejs 上传到 s3

postgresql - . 时如何将密码传递给 pg_dump 10主目录中的 pgpass 不是

angular - 找不到自定义管道 ionic 4 |找不到管道

c# - 如何从 dapper 返回的复杂对象中修剪所有字符串

angular - ng2图表多图表更新

macos - 如何在 macOS 上获取 awk 版本?

vue.js - 如何使用 Nuxt.js 在 vuex 状态中获取本地存储数据

python - 使用 Python 插入多个 MySQL 记录。错误 : "Python ' tu

python - 无法使用 python 3.72 连接 firebase

python - FlaskForm 验证码 : checking if a user alread