📜  在 Pandas 中从日期获取月份 - Python(1)

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

在 Pandas 中从日期获取月份 - Python

在 Pandas 中,我们可以使用 dt.month 获取日期中的月份。

import pandas as pd 

df = pd.DataFrame({'date': ['2021-01-01', '2021-02-01', '2021-03-01']})
df['date'] = pd.to_datetime(df['date'])
df['month'] = df['date'].dt.month

print(df)

输出结果:

        date  month
0 2021-01-01      1
1 2021-02-01      2
2 2021-03-01      3

使用 dt.month 可以方便地从日期中获取月份,同时还可以对日期进行其他操作,如获取年份、季度、星期等。

更多内容请参考 Pandas 官方文档:https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.month.html