我是Python的新手,开始使用Pandas替换MS Excel中完成的某些过程。
以下是我的问题描述
初始数据帧:
Contract Id, Start date, End date
12378, '01-01-2018', '15-05-2018'
45679, '10-03-2018', '31-07-2018'
567982, '01-01-2018', '31-12-2020'
预期产量
Contract Id , Start date, End date, Jan-18,Feb-18,Mar-18,Apr-18,May-18...Dec-18
12378, '01-01-2018', '15-05-2018', 1, 1, 1, 1, 1, 0, 0, 0, 0, .....,0
45679, '10-03-2018', '31-07-2018', 0, 0, 1, 1, 1, 1, 1, 0, 0, 0....,0
567982,'01-01-2018', '31-12-2020', 1, 1, 1, 1.........………..., 1, 1, 1
如果合同在指定月份内处于活动状态,我想用Month Id作为列标题创建一组新列,并用标志(1或0)填充它们。
任何帮助将不胜感激。谢谢
最佳答案
我也是熊猫的新手。也许有更好的方法可以做到这一点,但这就是我所拥有的:
data['S_month'] = data['S'].apply(lambda x:int(x.split('-')[1]))
data['E_month'] = data['E'].apply(lambda x:int(x.split('-')[1]))
months = []
for s_e in data[['S_month','E_month']].values:
month = np.zeros(12)
month[s_e[0]-1:s_e[1]] = 1
months.append(month)
months = pd.DataFrame(months,dtype=int,columns=np.arange(1,13))
data.join(months)
或者,您可以跳过前两行并执行以下操作:
months = []
for s_e in data[['S','E']].values:
month = np.zeros(12)
month[int(s_e[0].split('-')[1])-1:int(s_e[1].split('-')[1])] = 1
months.append(month)
months = pd.DataFrame(months,dtype=int,columns=np.arange(1,13))
data.join(months)
关于python - Python pandas数据框-将具有日期范围的2列转换为每个月的每月列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53759454/