Python学习指南——1.常用库说明
說在前面
在開發(fā)之前, 要去python庫官網(wǎng)上查看是否有幫助的庫。 結(jié)合百度和pypi.org網(wǎng)站直接尋找需要的庫。
庫安裝方法:1pip安裝 2.文件安裝:UCI頁面需要翻墻 ?https://www.lfd.uci.edu/~gohlke/pythonlibs 或者conda提供的那些網(wǎng)站也行。
文件安裝:下載UCI、whl文件之后,又要使用 pip install 文件來安裝 ?放到lib文件夾
vscode特殊:通常把要處理的文件放在一個(gè)工作文件下,方便輸出文件位置和調(diào)用。
一、文件操作
1.1 目錄庫 os: import os
os.path :用于獲取文件的基本信息
import os 輸出文件的絕對路徑:os.path.abspath(path); file_path = os.path.abspath('test.py') print(file_path) >>> c:\Users\YHW\Desktop\test_`1也可以直接存儲文件路徑:右鍵文件,屬性,查看完整地址復(fù)制過來 file_path = "C:\\Users\\YHW\\Desktop\\matlabprg" python中轉(zhuǎn)義字符在自己輸入時(shí)\\需要成對輸入,不然會有報(bào)錯(cuò),或者/反斜杠表示替代文件存在標(biāo)志:os.path.exists(path) 如果路徑 path 存在,返回 True;如果路徑 path 不存在,返回 False。 print(os.path.exists('test.py')) >>> True獲取工作文件夾路徑: print(os.getcwd()) c:\Users\YHW\Desktop\test_`1合并文件目錄路徑和文件名: file_path = os.path.join( os.getcwd(),"corpus_POS.txt" ) #據(jù)編譯器決定是否添加/分隔 print(file_path) c:\Users\YHW\Desktop\test_`1\corpus_POS.txtLinux系統(tǒng)下常見,把path中包含的"~"和"~user"轉(zhuǎn)換成用戶目錄: os.path.expanduser("路徑") 根據(jù)環(huán)境變量的值替換path中包含的"$name"和"${name}": os.path.expandvars("路徑")文件路徑切分成路徑和文件名: os.path.spilt("路徑") spilt并非os下才能使用! 返回一個(gè)元組,進(jìn)行讀取即可修改當(dāng)前工作文件夾目錄:
查看當(dāng)前工作目錄 file = os.getcwd(); file = print("當(dāng)前工作目錄為 %s" % file) >>> c:\Users\YHW\Desktop\test_`1修改當(dāng)前工作目錄 os.chdir( "c:\Users\YHW\Desktop\matlabprg" )返回某個(gè)文件夾中包含的文件名字的列表:
path = "c:\\Users\\YHW\\Desktop\\test_`1" dirs = os.listdir( path ) for file in dirs:print (file) >>> .vscode 1_tutorial_1or2hours.ipynb animalphoto dvsc.ipynb animal_model.h5 test.py創(chuàng)建文件夾:
path = "路徑" #一般與文件是否存在結(jié)合 os.path.exists(path) if(False):os.mkdir( path, 0755 )#0755mode設(shè)置權(quán)限,查表進(jìn)程管理:
進(jìn)程管理 python文件打開其他文件或者軟件的操作 調(diào)用其他程序 import os os.system("文件路徑") 還有許多其他的函數(shù) os.cpu_count() CPU數(shù)量 os.getlogin() 獲得用戶登錄名 print(os.getlogin()) print(os.path.abspath('kalman.py'))csv文件:二維列表? ? ?csv格式:逗號分割標(biāo)準(zhǔn)格式,類似表格
1.2 文件IO庫
——除了python自帶的open()函數(shù)以外,其他的庫都會提供自己的文件讀取流也可以。
pandas打開文件 import pandas as pd pd.read_excel("Excel文件路徑名") 用pandas可以打開各種文件numpy打開文件(僅npk:用于存儲重建 ndarray 所需的數(shù)據(jù)、圖形、dtype 和其他信息。) import numpy as np a = np.array([1,2,3,4,5]) np.save('outfile.npy',a) b = np.load('outfile.npy') print (b)也可以用open file_txt = open("路徑/文件名","r", encoding="utf-8").read() 參數(shù):文件位置、打開選項(xiàng)(讀寫選擇),編碼方式 file_txt.close()file = "c:\\Users\\YHW\\Desktop\\test_`1" f_test = open(file, "r", encoding="UTF-8") f_test = open(FILENAME, "r", encoding="UTF-8")realine讀入一行 f_test.readline() read讀取指定的字符大小 txt =f_test.read() readlines讀取所有行,每一行為一個(gè)字符串,所有字符串形成列表 list=[] list = f_test.readlines()寫一樣 f.write(string) f.writelines(list) f.seek(參數(shù))更改文件位置指針的位置文本數(shù)據(jù)的一個(gè)常規(guī)操作:for把每一行讀進(jìn)來,把每一行的末尾\n換成空格,然后每一行用逗號分割,用readlines()效果一樣
FILENAME = "machinelearning_add" fo = open(FILENAME, encoding="UTF-8") ls=[] for line in fo:line = line.replace("\n"," ")ls.append(line.split(",")) fo.close() ang=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] for item in ang:print(ls[item])輸出結(jié)果如下:
二、數(shù)組Numpy庫
2.1 創(chuàng)建數(shù)組,所有科學(xué)工具的基本: import numpy as np
創(chuàng)建數(shù)組,一維二維三維取決于內(nèi)部中括號個(gè)數(shù) a = np.array([[1,2,2],[2,5,7],[7,83,1]], dype = int) dytpe選擇內(nèi)部的數(shù)據(jù)類型,甚至可以表示復(fù)數(shù):complex64等 print (a) >>>[[ 1 2 2][ 2 5 7][ 7 83 1]]列表轉(zhuǎn)數(shù)組: a = [1,2,3,4,5] ma = np.array(a)注意區(qū)分“數(shù)組”和“矩陣”的區(qū)別,主要取決于數(shù)組類型和維度,下面的shape參數(shù)介紹結(jié)構(gòu)體數(shù)組:numpy 的數(shù)值類型實(shí)際上是 dtype 對象的實(shí)例,可以使用dype當(dāng)做初始化函數(shù) student = np.dtype([('age', 'int8'), ('marks', 'float')]) a = np.array([(21, 50),(18, 75)], dtype = student) print(a)創(chuàng)建數(shù)組,有序數(shù)組:arrange() a = np.arange(5) >>> [0 1 2 3 4]0,1元素?cái)?shù)組: numpy.zeros(shape, dtype = float, order = 'C') 默認(rèn)為浮點(diǎn)數(shù),order排序方式 numpy.ones(shape, dtype = None, order = 'C') x = np.ones([2,2], dtype = int) y = np.zeros((5,5), dtype = int) 自定義數(shù)據(jù)類型 z = np.zeros((2,2), dtype = [('x', 'int8'), ('y', 'float')]) print(z) z是二維矩陣,每一個(gè)元素是一個(gè)int和float組成的一個(gè)小元組元素。 >>> [[(0, 0.) (0, 0.)][(0, 0.) (0, 0.)]]2.2 創(chuàng)建矩陣:
import numpy as np
import numpy.matlib
零矩陣和1矩陣 numpy.matlib.zeros(2,3) numpy.matlib.ones(3,3)單位矩陣: numpy.matlib.eye() 函數(shù)返回一個(gè)矩陣,對角線元素為 1,其他位置為零。 print (np.matlib.eye(3, dtype = float)) >>> [[1. 0. 0.][0. 1. 0.][0. 0. 1.]]隨機(jī)矩陣: np.matlib.rand(3,3)2.3 數(shù)組工具:
數(shù)組的rank秩: ndarray.ndim調(diào)整大小,重構(gòu)數(shù)據(jù)大小reshape,重構(gòu)大小必須滿足!“列表轉(zhuǎn)數(shù)組 數(shù)組行列乘積個(gè)數(shù)一樣”兩個(gè)條件! a = np.arange(5) b = a.reshape(1,5) c = a.reshape(5,1)d = np.array([[1,2],[4,5],[6,89]]).reshape(3,2) f1 = np.arange(12).reshape(3,4) f2 = np.arange(12).reshape(2,6) >>> a = [0 1 2 3 4] [[0 1 2 3 4]][[0][1][2][3][4]]d = [[ 1 2][ 4 5][ 6 89]]f1 = [[ 0 1 2 3][ 4 5 6 7][ 8 9 10 11]]f2 = [[ 0 1 2 3 4 5][ 6 7 8 9 10 11]]數(shù)組格式,數(shù)組維度查看:shape print (e.shape) >>> (3, 2) 三行兩列 a = np.arange(5) a.shape >>> (5,) 列表型數(shù)組,和列表類似,但是不屬于矩陣,無法參與矩陣運(yùn)算其他類型轉(zhuǎn)數(shù)組(列表轉(zhuǎn)數(shù)組、元組轉(zhuǎn)數(shù)組等) a = range(0,5,1) a = np.asarray(a) print (a) >>> [0 1 2 3 4]2.4 數(shù)組的索引迭代、展平和組合:?
切片索引與列表一樣 a = np.arange(10) 從索引 2 開始到索引 7 停止,間隔為 2 b = a[2:7:2] 雙列索引 c = c[0:10, 2:6] 分號左邊是行索引,從0開始到10-1=9行;右邊列索引,從第2列開始到第5列 print(b,c)單個(gè)索引 f = np.arange(12).reshape(3,4) f = f.reshape(2,6) f[1][3]=522 >>> [[ 0 1 2 3 4 5][ 6 7 8 522 10 11]]訪問數(shù)組中的每一個(gè)元素:數(shù)組迭代循環(huán) nditer()有可選參數(shù) for x in np.nditer(a):print (x, end=", " )數(shù)組展平:展開數(shù)組,兩個(gè)函數(shù)拷貝與不拷貝的關(guān)系 ndarray.flatten() ndarray.ravel()找到列表中最大值的索引:最小值也是一樣(注意從0開始索引) a = [1,2,3,4,5] ma = np.array(a) a.index(max(ma))找到數(shù)組中的最大值: max = ma.max()找到最大值對應(yīng)的索引值(序號): 默認(rèn)axis是對整個(gè)數(shù)組索引,輸入axis就是按axis軸進(jìn)行最大值的索引 max = np.argmax(ma, axis = )轉(zhuǎn)置: b = 某個(gè)二維數(shù)組.T2.5 數(shù)組計(jì)算、矩陣計(jì)算:
運(yùn)算符直接使用:a*b? a+b a-b的結(jié)果就是 a 與 b 數(shù)組對應(yīng)位相乘。(按位乘)
觸發(fā)廣播機(jī)制,如果兩個(gè)數(shù)組維度不同,就把維度低的補(bǔ)齊到可以按位乘 a = np.array([[ 0, 0, 0],[10,10,10],[20,20,20],[30,30,30]]) b = np.array([1,2,3]) print(a * b) >>> [[ 0 0 0][10 20 30][20 40 60][30 60 90]]2.6 多維數(shù)組計(jì)算:通過np提供的方法才能進(jìn)行(與矩陣的運(yùn)算方法一樣)
矩陣乘法:dot()函數(shù)。矩陣乘法參考線性代數(shù) a = [[1, 0], [0, 1]] b = [[4, 1], [2, 2]] c=np.dot(a, b) >>> [[4 1][2 2]]a = [[1, 0], [0, 1]] b = [[4], [22]] c=np.dot(a, b) print(c) >>> [[ 4][22]]加減乘除:add(a,b),subtract(a,b),dot(a, b),divide(a,b)矩陣點(diǎn)積:對應(yīng)位置元素相乘 a = np.array([[1,2],[3,4]]) b = np.array([[11,12],[13,14]]) print (np.vdot(a,b))逆矩陣: x = np.array([[1,2],[3,4]]) y = np.linalg.inv(x) >>> [[-2. 1. ][ 1.5 -0.5]]2.7 其他計(jì)算函數(shù):
將整形轉(zhuǎn)換為其他進(jìn)制: print ('13 和 17 的二進(jìn)制形式:') a,b = 13,17 print (bin(a), bin(b)) print ('13 和 17 的位與:') print (np.bitwise_and(13, 17))>>> 13 和 17 的二進(jìn)制形式: 0b1101 0b1000113 和 17 的位與: 1bitwise_or()按位或 invert()取反 left_shift() 左移 同右移統(tǒng)計(jì)函數(shù): numpy.mean(ndarray) 平均數(shù) numpy.average(ndarray) 加權(quán)平均數(shù) np.std([1,2,3,4]) 標(biāo)準(zhǔn)差 np.var([1,2,3,4]) 方差???????三、繪圖庫matlpotlib
import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11) y = 2 * x + 5 z = 3 * x**2 + 2 plt.title("This is title don't support chinese") plt.xlabel("x axis ") plt.ylabel("y axis ") plt.plot(x,y,"ob") plt.plot(x,z,"-g") 繪圖命令 plt.show()通過plot后面的選項(xiàng)可以設(shè)置顏色和線段類型,下圖
?
四、 python其他常見庫:
4.1 random庫、時(shí)間函數(shù)庫:
#random庫的補(bǔ)充 import numpy as np #random的隨機(jī)庫生成數(shù)組形式的隨機(jī) import random as rd #1.設(shè)置了相同隨機(jī)數(shù)種子的隨機(jī)數(shù),會產(chǎn)生相同的隨機(jī)數(shù) #如果不設(shè)置種子,那么就會產(chǎn)生隨機(jī)的 rd.seed(10) a= rd.random() rd.seed(10) b = rd.random() c= rd.random() print(a, b, c) #2.各個(gè)函數(shù) rd.randint(1,5)#整數(shù)隨機(jī) rd.uniform(3,5)#產(chǎn)生a~b之間的隨機(jī)float數(shù) rd.shuffle([1,4,5,12,8])#隨機(jī)排序#時(shí)間函數(shù),包括獲取時(shí)間,性能優(yōu)化等 import time time.perf_counter()#復(fù)數(shù) z = 3.2 + 2.3j print(z.real, z.imag)pip install pyinstaller
常用的指令:
-F name,-onefile 產(chǎn)生單個(gè)的可執(zhí)行文件
-D dirname,--onedir 產(chǎn)生一個(gè)目錄(包含多個(gè)文件)作為可執(zhí)行程序
-i <xxx.ico> 產(chǎn)生的文件用xxx圖片作為圖標(biāo)
命令行里使用 ?pyinstaller -i <image_name.ico> -F file_name.py
總結(jié)
以上是生活随笔為你收集整理的Python学习指南——1.常用库说明的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: I want go to school
- 下一篇: 弹簧触摸开关原理图_10年老电工经验之谈