从Python Pandas的日期中获取月份
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
输出: