Python大数据编程PPT课件_第1页
Python大数据编程PPT课件_第2页
Python大数据编程PPT课件_第3页
Python大数据编程PPT课件_第4页
Python大数据编程PPT课件_第5页
已阅读5页,还剩95页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Python大数据编程,4数据分析,3数据描述,1数据收集,2数据整理,大数据处理过程,2,便捷数据获取,Python大数据编程,用Python获取数据,本地数据如何获取?文件的打开,读写和关闭文件打开读文件写文件文件关闭,4,用Python获取数据,网络数据如何获取?抓取网页,解析网页内容,urllib,urllib2,httplib,httplib2,5,Python3中被urllib.request代替,Python3中被http.client代替,yahoo财经数据,利用urllib库获取yahoo财经数据,File#Filename:dji.pyimporturllibimportredBytes=urllib.request.urlopen(,数据形式,包含多个字符串(dji)AXP,AmericanExpressCompany,86.40BA,TheBoeingCompany,122.24CAT,CaterpillarInc.,99.44CSCO,CiscoSystems,Inc.,23.78CVX,ChevronCorporation,115.91,便捷网络数据,是否能够简单方便并且快速的方式获得雅虎财经上各上市公司股票的历史数据?,File#Filename:quotes.pyfrommatplotlib.financeimportquotes_historical_yahoofromdatetimeimportdateimportpandasaspdtoday=date.today()start=(today.year-1,today.month,today.day)quotes=quotes_historical_yahoo_ochl(AXP,start,today)df=pd.DataFrame(quotes)printdf,函数目前更新为quotes_historical_yahoo_ochl,便捷网络数据,quotes的内容,日期,收盘价,开盘价,最高价,最低价,成交量,便捷网络数据,自然语言工具包NLTK,古腾堡语料库布朗语料库路透社语料库网络和聊天文本,fromnltk.corpusimportgutenbergimportnltk,printgutenberg.fileids(),uausten-emma.txt,uausten-persuasion.txt,uausten-sense.txt,ubible-kjv.txt,ublake-poems.txt,ubryant-stories.txt,uburgess-busterbrown.txt,ucarroll-alice.txt,uchesterton-ball.txt,uchesterton-brown.txt,uchesterton-thursday.txt,uedgeworth-parents.txt,umelville-moby_dick.txt,umilton-paradise.txt,ushakespeare-caesar.txt,ushakespeare-hamlet.txt,ushakespeare-macbeth.txt,uwhitman-leaves.txttexts=gutenberg.words(shakespeare-hamlet.txt)u,uThe,uTragedie,uof,uHamlet,uby,.,Source,brown,需要先执行nltk.download()下载某一个或多个包,若下,载失败,可以在官网(/nltk_data/),单独下载后放到本地python目录的nltk_datacorpora下,数据准备,Python大数据编程,数据形式,30支成分股(dji)股票数据的逻辑结构,美国运通公司(quotes)股票详细数据的逻辑结构,数据整理,quotes数据加属性名File#Filename:quotesproc.pyfrommatplotlib.financeimportquotes_historical_yahoo_ochlfromdatetimeimportdateimportpandasaspdtoday=date.today()start=(today.year-1,today.month,today.day)quotes=quotes_historical_yahoo_ochl(AXP,start,today)fields=date,open,close,high,low,volumequotesdf=pd.DataFrame(quotes,columns=fields)printquotesdf,数据整理,dji数据:加属性名,code,AXP,quotes数据:加属性名,数据整理,用1,2,作为索引,quotesdf=pd.DataFrame(quotes,columns=fields),quotesdf=pd.DataFrame(quotes,index=range(1,len(quotes)+1),columns=fields),数据整理,如果可以直接用date作为索引,quotes的时间能否转换成常规形式(如下图中的效果)?,Sourcefromdatetimeimportdatefirstday=date.fromordinal(735190)lastday=date.fromordinal(735551)firstdaydatetime.date(2013,11,18)lastdaydatetime.date(2014,11,14),时间序列,#Filename:quotesproc.pyfrommatplotlib.financeimportquotes_historical_yahoo_ochlfromdatetimeimportdatefromdatetimeimportdatetimeimportpandasaspdtoday=date.today()start=(today.year-1,today.month,today.day)quotes=quotes_historical_yahoo_ochl(AXP,start,today)fields=date,open,close,high,low,volume,list1=foriinrange(0,len(quotes):x=date.fromordinal(int(quotesi0)y=datetime.strftime(x,%Y-%m-%d)list1.append(y),quotesdf=pd.DataFrame(quotes,index=list1,columns=fields),quotesdf=quotesdf.drop(date,axis=1)printquotesdf,File,转换成常规时间,转换成固定格式,删除原date列,创建时间序列,importpandasaspddates=pd.date_range(20141001,periods=7)dates2014-10-01,.,2014-10-07Length:7,Freq:D,Timezone:Noneimportnumpyasnpdates=pd.DataFrame(np.random.randn(7,3),index=dates,columns=list(ABC)datesABC2014-10-011.302600-1.2147081.4116282014-10-02-0.5123432.2774740.4038112014-10-03-0.788498-0.2171610.1732842014-10-041.042167-0.453329-2.1071632014-10-05-1.6280751.6633770.9435822014-10-06-0.0910340.3358842.4554312014-10-07-0.679055-0.8659730.2469707rowsx3columns,Source,数据显示,Python大数据编程,数据显示,djidf,quotesdf,数据显示,显示方式:显示索引显示列名显示数据的值显示数据描述,数据显示,Sourcequotesdf.indexIndex(u2013-11-18,u2013-11-19,u2013-11-20,u2013-11-21,u2013-11-22,u2013-11-25,u2013-11-26,u2013-11-27,-04-08,u2014-04-09,u2014-04-10,u2014-04-11,.,dtype=object),索引的格式,数据显示,djidf.head(5),code,name,0AXPAmericanExpressCompany,1BA,2CAT,CSCOCVX,TheBoeingCompanyCaterpillarInc.CiscoSystems,Inc.ChevronCorporation,lasttrade90.67128.86101.3426.32116.32,5rowsx3columnsdjidf.tail(5),code,namelasttrade,25UTXUnitedTechnologiesCorporation,26VVisaInc.,27VZ,VerizonCommunicationsInc.,WMTXOM,Wal-MartStoresInc.ExxonMobilCorporation,107.45248.8451.5082.9695.09,5rowsx3columns,Source,df:5,df25:,显示方式:,显示行专用方式切片,查看道琼斯工业股中前5只和后5只的股票基本信息?,数据选择,Python大数据编程,数据选择,选择方式:选择行选择列选择区域筛选(条件选择),数据选择,5rowsx5columns,Sourcequotesdfu2013-12-02:u2013-12-06,选择方式:,选择行切片索引,美国运通公司2013年12月2日至2013年12月6日间的股票交易信息?,数据选择,AXPBACAT,01229XOM,Name:code,dtype:objectdjidf.code,01,AXPBA,CAT,229XOM,Name:code,dtype:object,Sourcedjidfcode,选择方式:,选择列列名,不支持djidfcode,lasttradedjidfcode:lasttrade,道琼斯工业股公司代码?,数据选择,选择方式:,行、列标签label(loc),5rowsx3columnsdjidf.loc:,code,lasttradecodelasttrade,0AXP,1BA,90.67128.862CAT101.3429XOM95.09,Sourcedjidf.loc1:5,道琼斯工业股中标号是1至5的股票信息以及所有股票的代码和最近一次交易价?,30rowsx2columns,数据选择,选择方式:,行和列的区域标签label(loc)单个值at,3CSCO,codelasttrade1BA128.862CAT101.3426.324CVX116.325DD70.80,5rowsx2columnsdjidf.loc1,lasttrade128.86djidf.at1,lasttrade128.86,Sourcedjidf.loc1:5,code,lasttrade,道琼斯工业股中标号是1至5的股票代码和最近一次交易价?标号是1的股票的最近一次交易价?,数据选择,选择方式:,行、列和区域,用iloc(位置),取某个值,iat,djidf.loc1:5,code,lasttrade,2CAT,CSCOCVX,codelasttrade1BA128.86101.3426.32116.325DD70.80,Source,djidf.loc1,lasttrade128.86djidf.at1,lasttrade128.86,Source,djidf.iloc1,2128.86djidf.iat1,2128.86,Source,数据选择,quotesdfquotesdf.index=u2014-01-01openclosehigh,lowvolume,221rowsx5columnsquotesdf(quotesdf.index=u2014-01-01)&(quotesdf.close=95),3rowsx5columns,Source,美国运通公司2014年的股票信息?进一步寻找美国运通公司2014年收盘价大于等于95的记录?,选择方式:条件筛选,简单统计与处理,Python大数据编程,简单统计与筛选,1TheBoeingCompany8TheGoldmanSachsGroup,Inc.10InternationalBusinessMachinesCorporation163MCompany26VisaInc.,Name:name,dtype:object,Sourcedjidf.mean(columns=lasttrade)lasttrade91.533667dtype:float64djidfdjidf.lasttrade=120.name,求道琼斯工业股中30只股票最近一次成交价的平均值?股票最近一次成交价大于等于120的公司名?,简单统计与筛选,Sourcelen(quotesdfquotesdf.closequotesdf.open)131len(quotesdf)-131120,统计美国运通公司近一年股票涨和跌分别的天数?,统计美国运通公司近一年相邻两天收盘价的涨跌情况?,Sourcestatus=np.sign(np.diff(quotesdf.close)statusarray(1.,-1.,1.,-1.,1.,1.,1.,1.,-1.,-1.,-1.,1.,1.,-1.,-1.,-1.)statusnp.where(status=1.).size130statusnp.where(status=-1.).size120,排序,djidf.sort(columns=lasttrade)code,namelasttrade,3CSCO,7GE,CiscoSystems,Inc.GeneralElectricCompany,26.3226.46,30rowsx3columnsdjidf.sort(columns=lasttrade)27:.name,10InternationalBusinessMachinesCorporation8TheGoldmanSachsGroup,Inc.26VisaInc.,Name:name,dtype:object,Source,按最近一次成交,价对30只道琼斯工业股股票进行排序。根据排序结果列出前三甲公司名。,可以添加sort()函数的ascending,属性控制顺序/逆序排序,默认该属性=True,即顺序排列,DataFrame的sort()函数已不推荐使用,相同功能推,荐使用sort_index()函数,计数统计,21rowsx5columnslen(t)21,Sourcet=quotesdf(quotesdf.index=2014-01-01)&(quotesdf.indext,统计2014年1月份的股票开盘天数?,计数统计,统计近一年每个月的股票开盘天数?,GROUPING,Python大数据编程,分组,Grouping的顺序SplittingApplyingCombining,分组,统计近一年每个月的股票开盘天数?,分组,统计近一年每个月的总成交量?,tempdf.groupby(month).sum().volumemonth,Source,mean()min()max(),11,67906300,12,67589400,Name:volume,dtype:float64,分组,如果更高效统计近一年每个月的总成交量?,12310,1048740007617380071488400120822100,Sourceg=tempdf.groupby(month)gvolume=gvolumeprintgvolume.sum()month,11,67906300,12,67589400,Name:volume,dtype:float64,MERGE,Python大数据编程,合并,Merge的形式Append加行到DataFrameConcat连接pandas对象JoinSQL类型的连接,Append,lowvolume,2rowsx5columnsq=quotesdfu2014-01-01:u2014-01-05q,openclosehighlowvolume,2014-01-0289.92443888.4990.10250688.42075151120002014-01-0388.18637788.7789.10632587.67199838885002rowsx5columnsp.append(q),4rowsx5columns,Sourcep=quotesdf:2popenclosehigh,把美国运通公司2014年1月1日至2014年1月5日间的股票交易信息合并到近一年中前两天的股票信息中?,Concat,将美国运通公司近一年股票数据中的前5个和后5个合并。,openclosehighlowvolumemonth,2013-11-1881.95448781.4582.08308281.2719463104800,11,11,2014-11-1790.24000090.1390.26000089.650000262050020rowsx6columns,Sourcepieces=tempdf:5,tempdflen(tempdf)-5:pd.concat(pieces),Concat,两个不同逻辑结构的对象能否连接?,6rowsx6columns,Sourcepiece1=quotesdf:3piece2=tempdf:3pd.concat(piece1,piece2,ignore_index=True),Join,Join,将美国运通公司和可口可乐公司近一年中每个月的交易总量表(包含公司代码)与30只道琼斯成分股股票信息合并。,code|name|month|volumes,Join,code,namelasttrade,volumemonth,24rowsx5columnspd.merge(djidf,AKdf,on=code).drop(lasttrade,axis=1),Sourcepd.merge(djidf,AKdf,on=code),merge函数的参数,条件,Python大数据编程,if语句,File#Filename:ifpro.pysd1=3sd2=3ifsd1=sd2:printthesquaresareais:%d%(sd1*sd2),ifexpression:expr_true_suite,语法,条件表达式:,比较运算符成员运算符逻辑运算符,expression,expression条件为True时执行的代码块代码块必须缩进(通常为4个空格),expr_true_suite,else语句,ifexpression:expr_true_suiteelse:expr_false_suite,语法,expression条件为False时执行的代码块代码块必须缩进else语句不缩进,expr_false_suite,File#Filename:elsepro.pysd1=int(raw_input(thefirstside:)sd2=int(raw_input(thesecondside:)ifsd1=sd2:printthesquaresareais:%d%(sd1*sd2)else:printtherectanglesareais:%d%(sd1*sd2)InputandOutputthefirstside:4thesecondside:4thesquaresareais:16,elif语句,ifexpression:expr_true_suiteelifexpression2:expr2_true_suite:elifexpressionN:exprN_true_suiteelse:none_of_the_above_suite,语法,expression2为True时执行的代码块,expr2_true_suite,expressionN为True时执行的代码块,exprN_true_suite,none_of_the_above_suite是以上所有条件都不满足时执行的代码块,else,elif语句,File#Filename:elifpro.pyk=raw_input(inputtheindexofshape:)ifk=1:printcircleelifk=2:printovalelifk=3:printrectangleelifk=4:printtriangleelse:printyouinputtheinvalidnumber,InputandOutputinputtheindexofshape:3rectangle,InputandOutputinputtheindexofshape:8youinputtheinvalidnumber,条件嵌套,File#Filename:ifnestpro.pyk=raw_input(inputtheindexofshape:)ifk=1:printcircleelifk=2:printovalelifk=3:sd1=int(raw_input(thefirstside:)sd2=int(raw_input(:thesecondside)ifsd1=sd2:printthesquaresareais:%d%(sd1*sd2)else:printtherectanglesareais:%d%(sd1*sd2)printrectangleelifk=4:printtriangleelse:printyouinputtheinvalidnumber,同等缩进为同一条件结构InputandOutputinputtheindexofshape:3thefirstside:3thesecondside:4therectanglesareais:12InputandOutputinputtheindexofshape:2oval,猜数字游戏,程序随机产生一个0300间的整数,玩家竞猜,系统给出“猜中”、“太大了”或“太小了”的提示。,File#Filename:guessnum1.pyfromrandomimportrandintx=randint(0,300)printPleaseinputanumberbetween0300:digit=input()ifdigit=x:printBingo!elifdigitx:printToolarge,pleasetryagain.else:printToosmall,pleasetryagain.,RANGE和XRANGE,Python大数据编程,range(),语法,起始值(包含),start,终值(不包含),end,步长(不能为0),step,不包含end的值,range(start,end,step=1),缺省step值为1,range(start,end),缺省了start值为0,step为1,range(end),range(start,end,step=1)range(start,end)range(end)生成一个真实的列表Sourcerange(3,11,2)3,5,7,9range(3,11)3,4,5,6,7,8,9,10range(11)0,1,2,3,4,5,6,7,8,9,10,xrange(),foriinxrange(3,11,2):printi,Sourcexrange(3,11,2)xrange(3,11,2)printxrange(3,11,2)xrange(3,11,2),Output:3579,在Python3.x中不支持xrange()函数,都使用range()函数,其返回值为range对象,并且需要显式调用,常用list(range(10)形式,循环,Python大数据编程,while循环,SourcesumA=0j=1whilejsumA45j10,whileexpression:suite_to_repeat,语法,条件表达式当expression值为True时执行suite_to_repeat代码块,expression,for循环(一),foriter_variniterable_object:suite_to_repeat,语法,遍历一个数据集内的成员在列表解析中使用生成器表达式中使用,可以明确循环的次数,StringListTupleDictionaryFile,iterable_object,for循环(二),字符串就是一个iterable_objectrange()返回的也是iterable_object,foriinrange(3,11,2):printi,3579,Sources=pythonforcins:printcpython,Python3.x中print函数用法与Python2.x中的语句用法也有所改变,例如此处变成print(i,end=),猜数字游戏,程序随机产生一个0300间的整数,玩家竞猜,允许猜多次,系统给出“猜中”、“太大了”或“太小了”的提示。,File#Filename:guessnum2.pyfromrandomimportrandintx=randint(0,300)forcountinrange(0,5):printPleaseinputanumberbetween0300:digit=input()ifdigit=x:printBingo!elifdigitx:printToolarge,pleasetryagain.else:printToosmall,pleasetryagain.,循环中的BREAK,CONTINUE和ELSE,Python大数据编程,break语句,break语句终止当前循环,转而执行循环之后的语句,File#Filename:breakpro.pysumA=0i=1whileTrue:sumA+=ii+=1ifsumA10:breakprinti=%d,sum=%d%(i,sumA),Output:i=6,sumA=15,while循环和break,输出2-100之间的素数,File#Filename:prime.pyfrommathimportsqrtj=2whilejk):printj,j+=1,Output:2357111317192329313741434753596167717379838997,for循环和break,File,输出2-100之间的素数,Output:2357111317192329313741434753596167717379838997,flag=1,#Filename:prime.pyfrommathimportsqrtforiinrange(2,101):k=int(sqrt(i)forjinrange(2,k+1):ifi%j=0:flag=0break,if(flag):printi,continue语句,在while和for循环中,continue语句的作用:停止当前循环,重新进入循环while循环则判断循环条件是否满足for循环则判断迭代是否已经结束,continue语句,循环中的break:File#Filename:breakpro.pysumA=0i=1whileik=5foriinrange(1,10):ifk=3:breakelse:printi9,Source,自定义函数,Python大数据编程,函数,函数调用之前必须先定义,内置函数,自定义函数,语法,自定义函数的创建,deffunction_name(arguments):optionaldocumentationstringfunction_suiteSourcedefaddMe2Me(x):applyoperation+toargumentreturn(x+x),自定义函数的调用,函数名加上函数运算符,一对小括号,括号之间是所有可选的参数即使没有参数,小括号也不能省略,addMe2Me(3.7)7.4addMe2Me(5)10addMe2Me(Python)PythonPython,Source,TypeError:addMe2Me()takesexactly1argument(0given),SourceaddMe2Me()Traceback(mostrecentcalllast):File,line1,inaddMe2Me(),自定义函数,输出1-100之间的素数,ifname=main:foriinrange(2,101):ifisprime(i):printi,File#Filename:prime.pyfrommathimportsqrtdefisprime(x):ifx=1:returnFalsek=int(sqrt(x)forjinrange(2,k+1):ifx%j=0:returnFalsereturnTrue,Output:2357111317192329313741434753596167717379838997,与Python2.x中一样,,用“ifname=,main”来判断,是否是在直接运行该.py文件,默认参数(一),函数的参数可以有一个默认值,如果提供有默认值,在函数定义中,默认参数以赋值语句的形式提供Sourcedeff(x=True):whetherxisacorrectwordornotifx:printxisacorrectwordprintOKf()xisacorrectwordOKf(False)OK,默认参数(二),默认参数的值可以改变,Sourcedeff(x,y=True):xandybothcorrectwordsornotify:printx,andybothcorrectprintx,isOKf(68)68andybothcorrect68isOKf(68,False)68isOK,默认参数(三),默认参数一般需要放置在参数列表的最后Sourcedeff(y=T

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论