简体   繁体   中英

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

I need some help in converting the columns to rows and name the columns dynamically by month.

Please see the attached raw_data image

For example: Let say the current month is March, the Demand00 month name would be March, Demand01 would be April and so on. If I run this same code in April, Demand00 column name should be named as April and Demand01 should be named as May and so on.

This is my first post, I hope I gave you the relevant information to seek help, if i had missed anything please let me know.

Thank you in advance for your help.

This should do:

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)

Line 1 extracts current month

Line 2 extracts every column that has 'Demand' in its name

Line 3 creates a list of Months from today's month to your last column's month and turns month as an integer into its month's name

Line 4 maps columns to months

Line 5 renames your columns.

Edit: added answer with month name instead of number

pd.DateOffset is nice to compute next months, and stack can convert columns to rows.

So code could be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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