【发布时间】: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