prev_month = pd.to_datetime(df['Month'],format='%m').sub(pd.Timedelta(1,unit='m')).dt.month
m = df.set_index(['Color','Month'])['Quantity']
final = (df.assign(Prev_Month_Value=pd.MultiIndex.from_arrays([df['Color'],prev_month])
.map(m).fillna(0)))
#To assign into the existing df,use below code instead of df.assign() which returns a copy
#df['Previous Month Value'] = (pd.MultiIndex.from_arrays([df['Color'],prev_month])
# .map(m).fillna(0)
df1 = df.pivot('Color','Month','Oty').reindex(columns=range(1,13))
print (df1)
Month 1 2 3 4 5 6 7 8 9 10 11 \
Color
1 34047.0 36654.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 NaN NaN 37291.0 35270.0 NaN NaN NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN 35407.0 NaN NaN NaN NaN NaN NaN
Month 12
Color
1 9300.0
2 NaN
3 NaN
以下是一种在查找上个月后使用^{} 和^{} 的方法:
输出:
详情:
使用^{} 重塑数据帧并通过^{} 添加完整月份:
然后将^{} 与^{} 一起使用:
下面是另一种使用^{} 的方法-我们将在} 内联:
prv_month
键上“合并”,我们将^{[外]
相关问题 更多 >
编程相关推荐