import datetime as dt
import calendar
this_month=dt.datetime.now().month
demand_columns=[i for i in df.columns if 'Demand' in i]
month_list=[calendar.month_name[this_month+i] for i in range(len(demand_columns))]
dic_month={col:month for col,month in zip(demand_columns,month_list)}
df.rename(columns=dic_month)
# compute month names:
cols = [x for x in df.columns if x.startswith('Demand')]
today = pd.Timestamp.now()
months=[(today+pd.DateOffset(months=i)).month_name()
for i in range(len(cols))]
# rename columns and stack:
df2 = pd.DataFrame(df.rename(columns=dict(zip(cols, months)))
.set_index('StockCode').stack()).reset_index()
df2.columns = ['StockCode', 'Month', 'Value']
这应该做到:
行1提取当月
第2行提取名称中包含“Demand”的每一列
第3行创建从今天的月份到最后一列月份的月份列表,并将月份作为整数转换为月份名称
第4行将列映射到月份
第5行重命名列。你知道吗
编辑:添加月份名称而不是数字的答案
pd.DateOffset
很适合在下个月进行计算,stack
可以将列转换为行。你知道吗所以代码可能是:
相关问题 更多 >
编程相关推荐