我已经堆积重建一个姓氏。 我透过这个数据帧。
from pandas import DataFrame,Series
d = {'Sex' : Series(["Male","Male","Female","Female","Female","Male"]),
'Rank' : Series(["A","B","C","A","B","C"]),
'Num' : Series([1,2,3,4,5,6]),
'States' : Series(["Ohio","Oregon","NC","Michigan","NY"])
}
df = DataFrame(d)
print df
df_pvt = df.pivot_table("Num",cols=['States','Sex'],rows="Rank")
print df_pvt
此数据框的列是ndarray。
print df_pvt.columns.values
type(df_pvt.columns.values)
我想将这些组合列重新组合成这样的组合列。
colnames = ['Michigan_Female','NC_Female','NY_Female','Ohio_Male','Oregon_Male']
我认为我必须制作一个func来组合这些列 但如果你知道这么简单的方法,请告诉我任何建议。
感谢阅读。
答案 0 :(得分:0)
最简单的方法可能是在旋转之前组合这些列:
In [17]: df['kind'] = df.States + '_' + df.Sex
In [18]: df.pivot_table('Num', cols=['kind'], rows='Rank')
Out[18]:
kind Michigan_Female NC_Female NY_Female Ohio_Male Oregon_Male
Rank
A 4 NaN NaN 1 NaN
B NaN NaN 5 NaN 2
C NaN 3 NaN NaN NaN