[python筆記]行列轉換,資料透視
阿新 • • 發佈:2019-02-06
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)