python - Python日期 - 迭代列名
问题描述
我正在将列名创建为字符串。名称代表从我的数据开始日期开始的年月(数据集本质上是一个矩阵,其中日期作为索引,“日期”字符串作为列名)
但是,我的代码不正确:
#date range index
output_frame_index = pd.date_range(min_date,periods = (months_of_data + future_prtiods), freq = 'M' )
#column names
cols = []
for i in range(months_of_data+1):
year = min_date.year + math.floor(i/12)
month = ( min_date.month + i) % 12
if not month: month = 12
col_label = str(year) + ' ' + str(month)
cols.append(col_label)
# create empty output frame
output_frame = pd.DataFrame(index = output_frame_index, columns = cols)
return output_frame
以上正确以“2011 3”作为第一列开始,但在“2011 12”之后迭代“2011 1”、“2011 2”、2012 3”。
先感谢您。
[编辑]
最终实施:
cols = [x.date().strftime('%Y_%m') for x in pd.date_range(min_date,periods=months_of_data,freq='M')]
基于下面的真棒答案。谢谢你。
解决方案
months_of_data = 24
min_date = '2018-01-01'
cols = (pd.date_range(min_date, periods=months_of_data, freq='M')
.strftime('%Y %-m') # '%Y %m' for 2018 01, 2018 02, ...
.tolist())
>>> cols
['2018 1',
'2018 2',
'2018 3',
'2018 4',
'2018 5',
'2018 6',
'2018 7',
'2018 8',
'2018 9',
'2018 10',
'2018 11',
'2018 12',
'2019 1',
'2019 2',
'2019 3',
'2019 4',
'2019 5',
'2019 6',
'2019 7',
'2019 8',
'2019 9',
'2019 10',
'2019 11',
'2019 12']
推荐阅读
- c++ - rabbitmq-c客户端的链接错误
- javascript - Javascript:'new Array(4)' 与 Array.apply(null, {length: 4}) 有何不同?
- c - C:在数组中存储对堆栈变量的引用
- c# - 引用在 Visual Studio 中未正确更新
- c# - 文件上传 HttpPostedFileBase null
- json - 如何从 JSON 字符串中删除子字符串
- python - 如何使用 python 访问 Postman 中的数组值
- php - 如何使用 php 在 json 中打印特定内容
- php - 如果验证失败问题,Laravel 5.6 返回请求数据
- sql - PL SQL CASE WHEN 语句