繁体   English   中英

如何在 Pandas 中取消旋转列并动态命名月份?

[英]How to unpivot columns in pandas and name the months dynamically?

我需要一些帮助来将列转换为行并按月动态命名列。

请参阅随附的raw_data 图像

例如:假设当前月份是三月,Demand00 月份名称将是三月,Demand01 将是四月等等。 如果我在 4 月运行相同的代码,Demand00 列名称应命名为 April,Demand01 应命名为 May,依此类推。

这是我的第一篇文章,我希望我给了你相关的信息来寻求帮助,如果我遗漏了什么,请告诉我。

预先感谢您的帮助。

这应该做:

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 行提取名称中包含“需求”的每一列

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

第 4 行将列映射到月份

第 5 行重命名您的列。

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

pd.DateOffset很适合计算pd.DateOffsetstack可以将列转换为行。

所以代码可能是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM