testxlsx=pd.ExcelWriter('test.xlsx')
for i in plat_360:
for j in range(0,len(needcolumns)):
if needcolumns[j]!='省份':
table=pd.pivot_table(data_cgm_360_copy_dropdup[data_cgm_360_copy_dropdup.plati],index='等级',columns=needcolumns[j],values='phone',aggfunc=f,margins=True)
for z in table.columns:
table[str(z)+'占比']=table[z]/table['All']
table[str(z)+'占比']=table[str(z)+'占比'].apply(lambda x:format(x*100,'.2f')+'%')
table.insert(0,'type',value=needcolumns[j])
title[title.index0].style.set_properties({'text-align':'center'}).to_excel(testxlsx,sheet_name=i,startrow=0,index=False)
dengjitable360=pd.pivot_table
(data_cgm_360_copy_dropdup[data_cgm_360_copy_dropdup.plat==i],index='等级',values='phone',aggfunc=f).rename(columns={'phone':'用户数'})
dengjitable360['用户数占比']=dengjitable360['用户数']/dengjitable360['用户数'].sum()
dengjitable360['用户数占比']=dengjitable360['用户数占比'].apply(lambda x:format(x*100,'.2f')+'%')
dengjitable360.style.set_properties().to_excel(testxlsx,sheet_name=i,startrow=83)
table.drop(columns='All占比').style.set_properties({'text-align':'center'}).to_excel(testxlsx,sheet_name=i,startrow=j*13+2)
pjnl=pd.pivot_table(data_cgm_360_copy_dropdup[data_cgm_360_copy_dropdup.plati],index='等级',values='年龄',aggfunc=np.mean).rename(columns={'年龄':'平均年龄'})
pjnl.to_excel(testxlsx,sheet_name=i,startrow=15,startcol=16)
else:
table=pd.pivot_table(data_cgm_360_copy_dropdup[data_cgm_360_copy_dropdup.plati],index='等级',columns=needcolumns[j],values='phone',aggfunc=f,margins=True)
table.insert(0,'type',value=needcolumns[j])
table.style.set_properties().to_excel(testxlsx,sheet_name=i,startrow=69)
setsheetwidth=testxlsx.sheets[i]
setsheetwidth.set_column('A:Q',16)
textxlsx.save()
标签:cgm,excel,循环,table,copy,data,dropdup,360 From: https://www.cnblogs.com/chenqianguan/p/17877958.html