I've stacked to remake a colnames. I pivot this dataframe.
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
The columns of this dataframe is ndarray.
print df_pvt.columns.values
type(df_pvt.columns.values)
I wanna remake colnames to such combined columns.
colnames = ['Michigan_Female','NC_Female','NY_Female','Ohio_Male','Oregon_Male']
I think that I have to make a func to combine these columns but if you know easy way to do this,please tell me any advise.
Thanks for reading.
The easiest way may be to combine those columns before pivoting:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.