预备阅读:Python使用xlrd和xlwt读写Excel的简单用法
前言
前面我们学习了简单的Python操作Excel的两个库xlrd和xlwt,今天来实际操作一个案例来增强实战功能。
案例背景
我们市场部的同学想通过分析广告投放时间前后(分钟级,前1分钟到后5分钟)的用户活跃数据来分析我们广告的投放效果,来决定是否继续投放和投放的其他选择性,所以他们需要我来帮忙计算一下数据。所以这里分享下实际操作。
数据准备
1、广告播放时间
这里的广告播放时间文件为ad.xlsx,由市场部同学提供,部分数据如下。
2、用户活跃数据
一般从数据库计算导出(SQL操作可以看我之前发布的MySQL相关知识),有时候也需要通过日志计算,已经计算好的数据uv.xlsx如下(分钟级)。这里我们区分了移动端和PC端。
数据计算
数据准备完毕之后,就可以直接计算了,因为前面已经说过xlrd和xlwt库的使用,这里直接贴上代码py_excel.py,大家可以实际操作试一试。
#coding:utf-8import xlrdimport xlwtimport reimport sysimport stringfrom datetime import datetime#read the ad play time dataprogramFile = r'ad.xls'#读取广告播放时间数据文件adFile = r'ad.xls'#打开文件并获取数据adWb = xlrd.open_workbook(adFile)adSheet = adWb.sheet_by_index(0)#获取目标时间列(在第3列,由日期和时间拼接而成)adTime = adSheet.col_values(2)lenth_of_time = len(adTime)#读取uv数据uvFile = r'uv.xls'uvWb = xlrd.open_workbook(uvFile)#数据存储在一张表时,如果有多个sheet,要分开赋值uvSheet = uvWb.sheet_by_index(0)uvTime = uvSheet.col_values(0)length = len(uvTime)#初始化写操作resultFile = xlwt.Workbook()#在生成表的时候添加了两张sheetresultMobile = resultFile.add_sheet('mobile',cell_overwrite_ok=True)resultPC = resultFile.add_sheet('PC',cell_overwrite_ok=True)i=1while(i-2and uvTime[4]-playTime[4]<6) or (uvTime[3]==playTime[3]+1 anduvTime[4]+60-playTime[4]>-2 and uvTime[4]+60-playTime[4]<6) or(uvTime[3]==playTime[3]-1 and uvTime[4]-59==0 and playTime[4]-0==0))) or(playTime[0]==uvTime[0] and playTime[1]==uvTime[1] and playTime[2]==uvTime[2]-1and uvTime[3]==0 and playTime[3]==23 and uvTime[4]+60-playTime[4]<6)): gap = uvTime[4]-playTime[4] if(gap
首行数据表示分钟。
![989e91a7f7444f49a88faa5d15f3745d](http://img-01.proxy.5ce.com/view/image?&type=2&guid=49d7d089-f62f-eb11-8da9-e4434bdf6706&url=https://p1.pstatp.com/large/pgc-image/989e91a7f7444f49a88faa5d15f3745d)
小结
上面就是今天的主题内容了,今天分享下如何使用Python操作Excel进行读写文件生成目标数据,方便后面进行数据分析。
欢迎关注公众号,访问更多精彩:数据之魅。