返回日期范围的数据框 [英] Return dataframe with range of dates
本文介绍了返回日期范围的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个Python函数来返回带有日期范围(仅包括年份和月份)的Pandas DataFrame,例如,从2016年11月到2017年3月,并得到以下结果:
I need a Python function to return a Pandas DataFrame with range of dates, only year and month, for example, from November 2016 to March 2017 and have this as result:
year month
2016 11
2016 12
2017 01
2017 02
2017 03
我的日期是字符串格式Y-m (from = '2016-11', to = '2017-03')
.我不确定将其转换为日期时间类型还是将其分为两个不同的整数值.
My dates are in string format Y-m (from = '2016-11', to = '2017-03')
. I'm not sure on turning them to datetime type or to separate them into two different integer values.
关于如何正确实现它的任何想法?
Any ideas on how to achieve it properly?
推荐答案
pd.Series(pd.date_range('2016-11', '2017-4', freq='M').strftime('%Y-%m')) \
.str.split('-', expand=True) \
.rename(columns={0: 'year', 1: 'month'})
year month
0 2016 11
1 2016 12
2 2017 01
3 2017 02
4 2017 03
这篇关于返回日期范围的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文