zip的作用:可以在处理循环时用到,返回一个将多个可迭代对象组合成一个元组序列的迭代器。每个元组都包含所有可迭代对象中该位置的元素:
letters=['a','b','c']nums=[1,2,3]forletter,numinzip(letters,nums):print("{}:{}".format(letter,num))结果:a:1b:2c:3enumerate是一个会返回元组迭代器的内置函数,这些元组包含列表的索引和值。当你需要在循环中获取可迭代对象的每个元素及其索引时,将经常用到该函数:
letters=['a','b','c','d','e']fori,letterinenumerate(letters):print(i,letter)结果:0a1b2c3d4e
1、tryexcept的使用
有时在写程序的时候,会出现一些错误或异常,导致程序终止。例如,做除法时,除数为0,会引起一个ZeroDivisionError
a=10b=0c=a/bprint("done")结果:ZeroDivisionError:divisionbyzero程序因为ZeroDivisionError而中断了,语句print"done"没有运行。为了处理异常,我们使用try...except,更改代码:
a=10b=0try:c=a/bprint(c)exceptZeroDivisionErrorase:print(e)finally:print('finally...')print("done")结果:divisionbyzerofinally...done
这样程序就不会因为异常而中断,从而print"done"语句正常执行。
总结:当我们认为某些代码可能会出错时,就可以用try来运行这段代码,如果执行出错,则后续代码不会继续执行,而是直接跳转至错误处理代码,即except语句块,执行完except后,如果有finally语句块,则执行finally语句块,至此,执行完毕。
注:当你有多个异常,可添加多个except,如:
try:print('try...')r=10/int('2')print('result:',r)exceptValueErrorase:print('ValueError:',e)exceptZeroDivisionErrorase:print('ZeroDivisionError:',e)else:print('noerror!')finally:print('finally...')print('END')异常类型:
2、python对文件的读写
读文件
打开一个文件用open()方法(open()返回一个文件对象,它是可迭代的):
f=open('/Users/gama/test.txt','r')标示符'r'表示读,这样,就成功地打开了一个文件。如果文件不存在,open()函数就会抛出一个IOError的错误
如果文件打开成功,接下来,调用read()方法可以一次读取文件的全部内容,Python把内容读到内存,用一个str对象表示:
f.close()由于文件读写时都有可能产生IOError,一旦出错,后面的f.close()就不会调用。所以,为了保证无论是否出错都能正确地关闭文件,我们可以使用try...finally来实现:
try:f=open('/path/to/file','r')print(f.read())finally:iff:f.close()但是每次都这么写实在太繁琐,所以,引入了with语句来自动帮我们调用close()方法:
withopen('/path/to/file','r')asf:print(f.read())这和前面的try...finally是一样的,但是代码更简洁,并且不必调用f.close()方法。
调用read()会一次性读取文件的全部内容,如果文件有10G,内存就爆了,所以,要保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。另外,调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list。因此,要根据需要决定怎么调用。
如果文件很小,read()一次性读取最方便;如果不能确定文件大小,反复调用read(size)比较保险;如果是配置文件,调用readlines()最方便:
forlineinf.readlines():print(line.strip())#把首末尾的'\n'或者空格删掉之前说的默认都是读取文本文件,并且是UTF-8编码的文本文件。要读取二进制文件,比如图片、视频等等,用'rb'模式打开文件即可:
f=open('/Users/gama/test.jpg','rb')要读取非UTF-8编码的文本文件,需要给open()函数传入encoding参数,例如,读取GBK编码的文件:
f=open('/Users/gama/gbk.txt','r',encoding='gbk')
写文件
写文件和读文件是一样的,唯一区别是调用open()函数时,传入标识符'w'或者'wb'表示写文本文件或写二进制文件:
f=open('/Users/gama/test.txt','w')f.write('Hello,python,thisisatest!')f.close()python读写模式
3、连接mysql数据库
创建一个函数来实现连接数据库,并且执行对应sql,并返回sql查询结果:
importpymysqlaspmsdefget_datas(sql):#一个传入sql导出数据的函数#跟数据库建立连接conn=pms.connect(host='实例地址',user='用户',passwd='密码',database='库名',port=3306,charset="utf8")#使用cursor()方法创建一个游标对象cursorcur=conn.cursor()#使用execute()方法执行SQLcur.execute(sql)#获取所需要的数据datas=cur.fetchall()#关闭连接cur.close()#返回所需的数据returndatas4、numpy
NumPy是一个Python包。它代表“NumericPython”。它是一个由多维数组对象和用于处理数组的例程集合组成的库。
使用NumPy,可以执行以下操作:
数组的算数和逻辑运算。
傅立叶变换和用于图形操作的例程。
与线性代数有关的操作。NumPy拥有线性代数和随机数生成的内置函数。
创建一个2维数组:
importnumpyasnpa=np.array([[1,2],[3,4]])print(a)numpy的数组属性:
ndarray.shape返回一个包含数组维度的元组,它也可以用于调整数组大小。
importnumpyasnpa=np.array([[1,2,3],[4,5,6]])print(a.shape)结果:(2,3)#调整数组大小importnumpyasnpa=np.array([[1,2,3],[4,5,6]])a.shape=(3,2)print(a)或者importnumpyasnpa=np.array([[1,2,3],[4,5,6]])b=a.reshape(3,2)print(b)ndarray.ndim返回数组的最小维数
importnumpyasnpa=np.array([[1,2,3],[4,5,6]])print(a.ndim)numpy.itemsize返回数组中每个元素的字节单位长度
#数组的dtype为int8(一个字节)importnumpyasnpx=np.array([1,2,3,4,5],dtype=np.int8)print(x.itemsize)numpy数组创建例程
numpy.empty创建指定形状和dtype的未初始化数组:
numpy.empty(shape,dtype=float,order='C')#Shape空数组的形状,整数或整数元组#Dtype所需的输出数组类型,可选#Order'C'为按行的C风格数组,'F'为按列的Fortran风格数组importnumpyasnpx=np.empty([3,2],dtype=int)print(x)numpy.zeros返回特定大小,以0填充的新数组:
numpy.zeros(shape,dtype=float,order='C')同理numpy.ones
现有数据转数组
numpy.array将Python序列转换为ndarray:
numpy.asarray(a,dtype=None,order=None)#a任意形式的输入参数,比如列表、列表的元组、元组、元组的元组、元组的列表#dtype通常,输入数据的类型会应用到返回的ndarray#order'C'为按行的C风格数组,'F'为按列的Fortran风格数组#将列表转换为ndarrayimportnumpyasnpx=[1,2,3]a=np.asarray(x)print(a)从数值范围创建数组
numpy.arange返回ndarray对象,包含给定范围内的等间隔值。
numpy.arange(start,stop,step,dtype)#start范围的起始值,默认为0#stop范围的终止值(不包含)#step两个值的间隔,默认为1#dtype返回ndarray的数据类型,如果没有提供,则会使用输入数据的类型。#设置了起始值和终止值参数importnumpyasnpx=np.arange(10,20,2)printx结果:[1012141618]numpy切片和索引
importnumpyasnpa=np.arange(10)s=slice(2,7,2)print(a[s])结果:[246]通过将由冒号分隔的切片参数(start:stop:step)直接提供给ndarray对象,也可以获得相同的结果。
切片还可以包括省略号(...):
#最开始的数组importnumpyasnpa=np.array([[1,2,3],[3,4,5],[4,5,6]])print('数组是:')print(a)print('\n')#这会返回第二列元素的数组:print('第二列的元素是:')print(a[...,1])print('\n')#现在我们从第二行切片所有元素:print('第二行的元素是:')print(a[1,...])print('\n')#现在我们从第二列向后切片所有元素:print('第二列及其剩余元素是:')print(a[...,1:])整数索引是整数数组表示该维度的下标值:
importnumpyasnpx=np.array([[1,2],[3,4],[5,6]])y=x[[0,1,2],[0,1,0]]print(y)结果:[145]该结果包括数组中(0,0),(1,1)和(2,0)位置处的元素。布尔索引:当结果对象是布尔运算(例如比较运算符)的结果时,将使用此类型的高级索引。
importnumpyasnpx=np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])print'我们的数组是:'printxprint'\n'#现在我们会打印出大于5的元素print'大于5的元素是:'printx[x>5]结果:我们的数组是:[[012][345][678][91011]]大于5的元素是:[67891011]5、pandas
安装pandas:
condainstallpandas#若已安装anacondapipinstallpandas#未安装anacondaPandas的主要数据结构:
Series创建:
系列(Series)是能够保存任何类型的数据(整数,字符串,浮点数,Python对象等)的一维标记数组。轴标签统称为索引。
importpandasaspdimportnumpyasnp#创建Seriesa1=pd.Series([1,2,3])#数组生成Seriesa2=pd.Series(np.array([1,2,3]))#numpy数组生成Seriesa3=pd.Series([1,2,3],index=["index1","index2","index3"])#指定标签index生成a4=pd.Series({"index1":1,"index2":2,"index3":3})#字典生成Seriesa5=pd.Series({"index":1,"index2":2,"index3":3},index=["index1","index2","index3"])#字典生成Series,指定index,不匹配部分为NaNa6=pd.Series(10,index=["index1","index2","index3"])Series属性:
a1=pd.Series([1,2,3])index=a1.index#Series索引values=a1.values#Series数值a1.name="population"#指定Series名字a1.index.name="state"#指定Series索引名字Series查找元素:
a3=pd.Series([1,2,3],index=["index1","index2","index3"])#查找元素value1=a3["index1"]#索引查找元素value2=a3.index1#键值索引查找元素value3=a3[0]#绝对位置查找元素value4=a3[["index1","index2"]]#花式索引value5=a3[[0,1]]#花式索引value6=a3[a3>np.mean(a3)]#布尔值查找元素value7=a3[0:2]#绝对位置切片value8=a3["index1":"index3"]#索引切片Series修改元素:
#修改元素a3["index3"]=100#按照索引修改元素a3[2]=1000#按照绝对位置修改元素Series添加元素:
#添加元素a3["index4"]=10#按照索引添加元素Series删除元素:
a3.drop(["index4","index3"],inplace=True)#inplace=True表示作用在当前Seriesprint(a3)#index11index22Series方法:
a3=pd.Series([1,2,3],index=["index1","index2","index3"])a3["index3"]=np.NaN#添加元素a3.isnull()#判断Series是否有缺失值a3.notnull()#判断Series是否没有缺失值print("index1"ina3)#判断Series中某个索引是否存在a3.isin([1])#判断Series中某个值是否存在a3.unique()#统计Series中去重元素a3.value_counts()#统计Series中去重元素和个数数据帧(DataFrame)是二维数据结构,即数据以行和列的表格方式排列。
数据帧(DataFrame)的功能特点:
df.set_index('Day',inplace=True)输出结果:BounceRateVisitorsDay1654326734378654655654529从列表来创建DataFrame:
importpandasaspddata=[['Alex',10],['Bob',12],['Clarke',13]]df=pd.DataFrame(data,columns=['Name','Age'],dtype=float)print(df)从系列的字典来创建DataFrame:
importpandasaspdd={'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([1,2,3,4],index=['a','e','c','d'])}df=pd.DataFrame(d)print(df)结果:onetwoa1.01.0b2.0NaNc3.03.0dNaN4.0eNaN2.0DataFrame选择和切片:
importpandasaspdd={'one':pd.Series([1,2,3],index=['a','b','c']),'two':pd.Series([1,2,3,4],index=['a','b','c','d'])}df=pd.DataFrame(d)print(df['one'])#列选择df['three']=pd.Series([10,20,30],index=['a','b','c'])#列添加deldf['one']#列删除df.pop('two')#列删除print(df.loc['b'])#行选择print(df[2:4])#行切片df2=pd.DataFrame([[5,6],[7,8]],columns=['one','two'])df=df.append(df2)#行添加df=df.drop('a')#删除行print(df.loc[:,['one','two']])#表示选取所有的行以及columns为'one','two'的列DataFrame转置
importpandasaspdimportnumpyasnp#CreateaDictionaryofseriesd={'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Minsu','Jack']),'Age':pd.Series([25,26,25,23,30,29,23]),'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}#CreateaDataFramedf=pd.DataFrame(d)print("before:")print(df)print("after:")print(df.T)print(df.axes)#返回轴标签和列轴标签列表DataFrame统计性描述
importpandasaspdimportnumpyasnp#CreateaDictionaryofseriesd={'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Minsu','Jack','Lee','David','Gasper','Betina','Andres']),'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])}#CreateaDataFramedf=pd.DataFrame(d)print(df.describe())结果:AgeRatingcount12.00000012.000000mean31.8333333.743333std9.2326820.661628min23.0000002.56000025%25.0000003.23000050%29.5000003.79000075%35.5000004.132500max51.0000004.800000统计函数:
面板(Panel)是3D容器的数据
pandas.Panel(data,items,major_axis,minor_axis,dtype,copy)3轴(axis)这个名称旨在给出描述涉及面板数据的操作的一些语义。它们是:
#creatinganemptypanelimportpandasaspdimportnumpyasnpdata={'Item1':pd.DataFrame(np.random.randn(4,3)),'Item2':pd.DataFrame(np.random.randn(4,2))}p=pd.Panel(data)print(p)要从面板中访问数据,可以使用以下方式:
#creatinganpanelimportpandasaspdimportnumpyasnpdata={'Item1':pd.DataFrame(np.random.randn(4,3)),'Item2':pd.DataFrame(np.random.randn(4,2))}p=pd.Panel(data)print(p['Item1'])print(p.major_xs(1))print(p.minor_xs(1))
pandas读写文件
data=pd.read_csv("data.txt")#从文件、URL、文件新对象中加载带有分隔符的数据,默认分隔符是逗号。data=pd.read_table("data.txt",sep=",")#从文件、URL、文件型对象中加载带分隔符的数据,默认分隔符为制表符("\t")文件没有标题:data1=pd.read_csv("data.txt",header=None)#设置header参数,读取文件的时候没有标题data2=pd.read_csv("data.txt",names=["a","b","c","d","name"])#设置names参数,来设置文件的标题使用pandas在读取文件的时候,pandas会默认将NA、-1.#IND、NULL等当作是缺失值,pandas默认使用NaN进行代替。data1=pd.read_csv("data.txt",na_values=["a","b"])#读取含有缺失值文件时,将指定的值替换缺失值读取函数写入函数read_csvto_csvread_excelto_excelread_hdfto_hdfread_sqlto_sqlread_jsonto_jsonread_htmlto_htmlread_statato_stataread_clipboardto_clipboardread_pickleto_pickleread_msgbackto_msgbackread_bbqto_gbq
6、python画图
为了能够显示图表,首先需要安装matplotlib库。
折线图:
importnumpyasnpimportpandasaspdimportmatplotlib.pyplotasplt#产生1000个4列正态分布的随机数data=pd.DataFrame(np.random.randn(1000,4))#对其中的数据进行累加,目的是为了能够使例子中显示的曲线有上升波动效果data=data.cumsum()#打印出前几行的数据,方便我们调试其中的数据值print(data.head())#画图表data.plot()#显示图表plt.show()
散点图:
importnumpyasnpimportpandasaspdimportmatplotlib.pyplotasplt#产生1000个4列正态分布的随机数data=pd.DataFrame(np.random.randn(1000,4),columns=list("ABCD"))#打印出前几行的数据,方便我们调试其中的数据值print(data.head())#显示散点图data.plot.scatter(x='A',y='B')#显示图plt.show()直方图:
#-*-coding:utf-8-*-importmatplotlib.pyplotaspltsalary=[2500,3300,2700,5600,6700,5400,3100,3500,7600,7800,8700,9800,10400]group=[1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000]plt.hist(salary,group,histtype='bar',rwidth=0.8)plt.legend()plt.xlabel('salary-group')plt.ylabel('salary')plt.title(u'测试例子——直方图')plt.show()