在将多列转换为单独的观测值时,我需要一些帮助。上次在您的帮助下,我尝试转换“需求”列,现在我必须添加更多列,例如“乔布斯”和“采购订单12”列,并希望将其转换为三个单独的观察值,然后再计算“未来自由”列(“自由未来=最大(工作,PO)-需求)
from sqlalchemy import create_engine
import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
import calendar
from pandas.tseries.offsets import MonthEnd
engine = create_engine('mssql+pyodbc://server/driver=SQL+Server')
con=engine.connect()
rs=con.execute("""Select StockCode, Demand00, Demand01, Demand02,
Demand03, Demand04, Demand05, Demand06, Demand07, Demand08, Demand09,
Demand10, Demand11 from ForecastData""")
df= pd.DataFrame(rs.fetchall())
df.columns = ["StockCode", "Demand01","Demand02", "Demand03", "Demand04",
"Demand05", "Demand06","Demand07", "Demand08", "Demand09", "Demand10",
"Demand11", "Demand12"]
df.set_index('StockCode')
demand_columns=[i for i in df.columns if i.startswith('Demand')]
today=pd.Timestamp.now()
month_list=[(today+pd.DateOffset(months=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)
df2=pd.DataFrame(df.rename(columns=dict(zip(demand_columns,month_list))).set_
index('StockCode').stack()).reset_index()
df2.columns = ['StockCode', 'Month', 'Value']
df2['Month'] = pd.to_datetime(df2['Month'], format = '%Y%m').dt.date
上一个输出
StockCode Month Value
ABC 2019-01-01 100
ABC 2019-02-01 80
BXY 2019-01-01 50
所需的输出
StockCode Month Demand Job PO FutureFree
ABC January 100 120 0 20
ABC February 120 80 0 0
BXY January 50 00 60 10