如何在pandas中取消pivot列并动态命名月份?

2024-04-20 11:49:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些帮助来将列转换成行,并按月份动态命名列。你知道吗

请参阅附件raw_data image

例如:假设当前月份是三月,Demand00 month name将是三月,Demand01将是四月,依此类推。如果我在四月运行相同的代码,Demand00列名应该命名为April,Demand01应该命名为May,依此类推。你知道吗

这是我的第一篇帖子,希望我给你提供相关信息寻求帮助,如果我有什么遗漏请让我知道。你知道吗

事先谢谢你的帮助。你知道吗


Tags: 代码nameimagedata附件raw请参阅动态
2条回答

这应该做到:

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)

行1提取当月

第2行提取名称中包含“Demand”的每一列

第3行创建从今天的月份到最后一列月份的月份列表,并将月份作为整数转换为月份名称

第4行将列映射到月份

第5行重命名列。你知道吗

编辑:添加月份名称而不是数字的答案

pd.DateOffset很适合在下个月进行计算,stack可以将列转换为行。你知道吗

所以代码可能是:

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

相关问题 更多 >