利用pandas计算一月至今的所有月份(欢迎其他方法,未有时间找到答案)
作者:互联网
import pandas as pd
from datetime import datetime
# calculate the year and month from '2021-01-01' to now
df = pd.DataFrame(pd.date_range('2021-01-01', datetime.now(), freq='M'), columns=['begin_month'])
# offset the month by 1
df['end_month'] = df['begin_month'] + pd.DateOffset(months=1)
# revise the format of the month
df['begin_month'] = df['begin_month'].apply(lambda x: x.strftime('%Y-%m-01'))
df['end_month'] = df['end_month'].apply(lambda x: x.strftime('%Y-%m-01'))
print(df)
result
标签:begin,01,end,df,一月,month,未有,pd,pandas 来源: https://blog.csdn.net/foxirensheng/article/details/122388627