首页 > 解决方案 > 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')]

基于下面的真棒答案。谢谢你。

标签: pythonpandasdatedataframeiteration

解决方案


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']

推荐阅读