在 Pandas 中从日期获取月份 - Python
Pandas有许多内置方法,可用于从给定日期中提取月份,这些方法是使用random函数或使用Timestamp函数随机生成的,或者使用to_datetime函数转换为日期格式。让我们看几个例子以便更好地理解。
示例 1
import pandas as pd
dti = pd.date_range('2020-07-01', periods = 4, freq ='M')
print(dti.month)
输出:
Int64Index([7, 8, 9, 10], dtype='int64')
示例 2
import pandas as pd
import numpy as np
import datetime
date1 = pd.Series(pd.date_range('2020-7-1 12:00:00', periods = 5))
df = pd.DataFrame(dict(date_given = date1))
df['month_of_date'] = df['date_given'].dt.month
df
输出:
示例 3
import pandas as pd
import datetime
import numpy as np
dates =['14 / 05 / 2017', '2017', '07 / 09 / 2017']
frame = pd.to_datetime(dates, dayfirst = True)
frame = pd.DataFrame([frame]).transpose()
frame['date']= frame
frame['month']= frame['date'].dt.month
frame.drop(0, axis = 1, inplace = True)
frame
输出: