import pandas as pd
import numpy as np
a0=[['亨利','男','语文',98.],['C罗','男','体育',60.],['亨利','男','数学',60.],['C罗','男','语文',100.]]
af0 = pd.DataFrame(a0,columns=['name','sex','lesson','score'])
'''
score avg
lesson 体育 数学 语文
name sex
C罗 男 60.0 0.0 100.0 80.0
亨利 男 0.0 60.0 98.0 79.0
'''
af = af0.set_index(['name','sex','lesson'],inplace=False)
af = af.unstack()
af['avg']=af.mean(axis=1,skipna=True)
af[af.isnull()]=0
af2 = af0.pivot(index='name',columns='lesson',values='score')
af2['avg']=af2.mean(axis=1)
af2.fillna(0,inplace=True)
af3=af0.pivot_table(values='score',index=['name','sex'],columns='lesson',aggfunc=np.mean,margins=True,fill_value=0)
print(af3)