excel 循环

发布时间 2023-12-05 19:20:52作者: 广爷天下无双

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.index
0].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.plat
i],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)