【问题标题】:Python date - iterative column namesPython日期 - 迭代列名
【发布时间】:2020-02-13 21:35:15
【问题描述】:

我将列名创建为字符串。名称代表从我的数据开始日期开始的年月(数据集本质上是一个矩阵,以日期为索引,“日期”字符串作为列名)

但是,我的代码不正确:

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

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

【问题讨论】:

标签: python pandas date dataframe iteration


【解决方案1】:
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']

【讨论】:

    猜你喜欢
    • 2017-09-04
    • 2017-12-14
    • 2019-01-15
    • 2014-05-19
    • 2018-10-22
    • 2023-03-15
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多