[python笔记]行列转换,数据透视

import pandas as pd
import numpy as np

a0=[['亨利','男','语文',98.],['C罗','男','体育',60.],['亨利','男','数学',60.],['C罗','男','语文',100.]]
af0 = pd.DataFrame(a0,columns=['name','sex','lesson','score'])
# print(af0)
#目标转化成
'''
         score                avg
lesson      体育    数学     语文
name sex
C罗   男    60.0   0.0  100.0  80.0
亨利   男     0.0  60.0   98.0  79.0

'''
#方法1set_index unstack()
af = af0.set_index(['name','sex','lesson'],inplace=False)
af = af.unstack()
af['avg']=af.mean(axis=1,skipna=True)
af[af.isnull()]=0
# print(af)
#方法2 pivot
af2 = af0.pivot(index='name',columns='lesson',values='score')
af2['avg']=af2.mean(axis=1)
af2.fillna(0,inplace=True)
# print(af2)
#方法3pivottable
af3=af0.pivot_table(values='score',index=['name','sex'],columns='lesson',aggfunc=np.mean,margins=True,fill_value=0)
print(af3)

你可能感兴趣的:(python)