我有一个关于重新排列数据透视表中的列的问题。我想按月对列进行分组,但安排如下:
JAN FEB
X,Y,X/Y X,Y,X/Y ....
当前输出为:
JAN FEB JAN FEB JAN ...
X X ... Y Y ... X/Y ...
在构建具有多列的数据透视表时,我注意到在 Excel 中实现的相同行为。
请参阅下面的示例。输出具有第一种格式。谢谢
from pandas import DataFrame,pivot_table
import numpy as np
from datetime import datetime
names=["a","b","c","a","b"]
dates=["20/01/2013","21/01/2013","22/02/2013", "01/03/2013","01/03/2013"]
dico={"x":[1,3,5,7,9], "y":[2,4,6,8,10], "date":dates, "name":names}
df=DataFrame(dico)
df["month"]=[datetime.strptime(x,'%d/%m/%Y').month for x in dates ]
print df
mpivot=pivot_table(df, values=["x","y"],cols=["month"], rows="name",aggfunc=np.sum)
print mpivot