背景
什麼是 NumPy 呢?
NumPy 這個詞來源於兩個單詞 – Numerical
和Python
。其是一個功能強大的 Python 庫,可以幫助程序員輕鬆地進行數值計算,通常應用於以下場景:
- 執行各種數學任務,如:數值積分、微分、內插、外推等。因此,當涉及到數學任務時,它形成了一種基於 Python 的 MATLAB 的快速替代。
- 計算機中的圖像表示爲多維數字數組。NumPy 提供了一些優秀的庫函數來快速處理圖像。例如,鏡像圖像、按特定角度旋轉圖像等。
- 在編寫機器學習算法時,需要對矩陣進行各種數值計算。如:矩陣乘法、求逆、換位、加法等。NumPy 數組用於存儲訓練數據和機器學習模型的參數。
輸入和輸出
numpy 二進制文件
save()
、savez()
和load()
函數以 numpy 專用的二進制類型(npy、npz)保存和讀取數據,這三個函數會自動處理ndim、dtype、shape等信息,使用它們讀寫數組非常方便,但是save()
輸出的文件很難與其它語言編寫的程序兼容。
npy格式:以二進制的方式存儲文件,在二進制文件第一行以文本形式保存了數據的元信息(ndim,dtype,shape等),可以用二進制工具查看內容。
npz格式:以壓縮打包的方式存儲文件,可以用壓縮軟件解壓。
numpy.save(file, arr, allow_pickle=True, fix_imports=True)
Save an array to a binary file in NumPy.npy
format.numpy.load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII')
Load arrays or pickled objects from.npy
,.npz
or pickled files.
【例】
import numpy as np
outfile = r'.\test.npy'
np.random.seed(20200619)
x = np.random.uniform(0, 1, [3, 5])
np.save(outfile, x)
y = np.load(outfile)
print(y)
# [[0.01123594 0.66790705 0.50212171 0.7230908 0.61668256]
# [0.00668332 0.1234096 0.96092409 0.67925305 0.38596837]
# [0.72342998 0.26258324 0.24318845 0.98795012 0.77370715]]
numpy.savez(file, *args, **kwds)
Save several arrays into a single file in uncompressed.npz
format.
savez()
第一個參數是文件名,其後的參數都是需要保存的數組,也可以使用關鍵字參數爲數組起一個名字,非關鍵字參數傳遞的數組會自動起名爲arr_0, arr_1, …
。
savez()
輸出的是一個壓縮文件(擴展名爲npz),其中每個文件都是一個save()
保存的npy文件,文件名對應於數組名。load()
自動識別npz文件,並且返回一個類似於字典的對象,可以通過數組名作爲關鍵字獲取數組的內容。
【例】將多個數組保存到一個文件,可以使用numpy.savez()
函數。
import numpy as np
outfile = r'.\test.npz'
x = np.linspace(0, np.pi, 5)
y = np.sin(x)
z = np.cos(x)
np.savez(outfile, x, y, z_d=z)
data = np.load(outfile)
np.set_printoptions(suppress=True)
print(data.files)
# ['z_d', 'arr_0', 'arr_1']
print(data['arr_0'])
# [0. 0.78539816 1.57079633 2.35619449 3.14159265]
print(data['arr_1'])
# [0. 0.70710678 1. 0.70710678 0. ]
print(data['z_d'])
# [ 1. 0.70710678 0. -0.70710678 -1. ]
用解壓軟件打開 test.npz 文件,會發現其中有三個文件:arr_0.npy,arr_1.npy,z_d.npy
,其中分別保存着數組x,y,z
的內容。
文本文件
savetxt()
,loadtxt()
和genfromtxt()
函數用來存儲和讀取文本文件(如TXT,CSV等)。genfromtxt()
比loadtxt()
更加強大,可對缺失數據進行處理。
-
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)
Save an array to a text file.- fname:文件路徑
- X:存入文件的數組。
- fmt:寫入文件中每個元素的字符串格式,默認’%.18e’(保留18位小數的浮點數形式)。
- delimiter:分割字符串,默認以空格分隔。
-
numpy.loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None)
Load data from a text file.- fname:文件路徑。
- dtype:數據類型。
- skiprows:跳過多少行,一般跳過第一行表頭。
- usecols:讀取指定的列,索引,元組類型。
- unpack:當加載多列數據時是否需要將數據列進行解耦賦值給不同的變量。
【例】寫入和讀出TXT文件。
import numpy as np
outfile = r'.\test.txt'
x = np.arange(0, 10).reshape(2, -1)
np.savetxt(outfile, x)
y = np.loadtxt(outfile)
print(y)
# [[0. 1. 2. 3. 4.]
# [5. 6. 7. 8. 9.]]
test.txt文件如下:
0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00 4.000000000000000000e+00
5.000000000000000000e+00 6.000000000000000000e+00 7.000000000000000000e+00 8.000000000000000000e+00 9.000000000000000000e+00
【例】寫入和讀出CSV文件。
import numpy as np
outfile = r'.\test.csv'
x = np.arange(0, 10, 0.5).reshape(4, -1)
np.savetxt(outfile, x, fmt='%.3f', delimiter=',')
y = np.loadtxt(outfile, delimiter=',')
print(y)
# [[0. 0.5 1. 1.5 2. ]
# [2.5 3. 3.5 4. 4.5]
# [5. 5.5 6. 6.5 7. ]
# [7.5 8. 8.5 9. 9.5]]
test.csv文件如下:
0.000,0.500,1.000,1.500,2.000
2.500,3.000,3.500,4.000,4.500
5.000,5.500,6.000,6.500,7.000
7.500,8.000,8.500,9.000,9.500
genfromtxt()
是面向結構數組和缺失數據處理的。
numpy.genfromtxt(fname, dtype=float, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=''.join(sorted(NameValidator.defaultdeletechars)), replace_space='_', autostrip=False, case_sensitive=True, defaultfmt="f%i", unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding='bytes')
Load data from a text file, with missing values handled as specified.- names:設置爲True時,程序將把第一行作爲列名稱。
data.csv文件如下:
id,value1,value2,value3
1,123,1.4,23
2,110,0.5,18
3,164,2.1,19
【例】
import numpy as np
outfile = r'.\data.csv'
x = np.loadtxt(outfile, delimiter=',', skiprows=1)
print(x)
# [[ 1. 123. 1.4 23. ]
# [ 2. 110. 0.5 18. ]
# [ 3. 164. 2.1 19. ]]
x = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2))
print(x)
# [[123. 1.4]
# [110. 0.5]
# [164. 2.1]]
val1, val2 = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2), unpack=True)
print(val1) # [123. 110. 164.]
print(val2) # [1.4 0.5 2.1]
【例】
import numpy as np
outfile = r'.\data.csv'
x = np.genfromtxt(outfile, delimiter=',', names=True)
print(x)
# [(1., 123., 1.4, 23.) (2., 110., 0.5, 18.) (3., 164., 2.1, 19.)]
print(type(x))
# <class 'numpy.ndarray'>
print(x.dtype)
# [('id', '<f8'), ('value1', '<f8'), ('value2', '<f8'), ('value3', '<f8')]
print(x['id']) # [1. 2. 3.]
print(x['value1']) # [123. 110. 164.]
print(x['value2']) # [1.4 0.5 2.1]
print(x['value3']) # [23. 18. 19.]
data1.csv文件
id,value1,value2,value3
1,123,1.4,23
2,110,,18
3,,2.1,19
【例】
import numpy as np
outfile = r'.\data1.csv'
x = np.genfromtxt(outfile, delimiter=',', names=True)
print(x)
# [(1., 123., 1.4, 23.) (2., 110., nan, 18.) (3., nan, 2.1, 19.)]
print(type(x))
# <class 'numpy.ndarray'>
print(x.dtype)
# [('id', '<f8'), ('value1', '<f8'), ('value2', '<f8'), ('value3', '<f8')]
print(x['id']) # [1. 2. 3.]
print(x['value1']) # [123. 110. nan]
print(x['value2']) # [1.4 nan 2.1]
print(x['value3']) # [23. 18. 19.]
文本格式選項
numpy.set_printoptions(precision=None,threshold=None, edgeitems=None,linewidth=None, suppress=None, nanstr=None, infstr=None,formatter=None, sign=None, floatmode=None, **kwarg)
Set printing options.precision
:設置浮點精度,控制輸出的小數點個數,默認是8。threshold
:概略顯示,超過該值則以“…”的形式來表示,默認是1000。suppress
:當suppress=True
,表示小數不需要以科學計數法的形式輸出,默認是False。nanstr
: String representation of floating point not-a-number,默認nan
。infstr
:String representation of floating point infinity,默認inf
。
These options determine the way floating point numbers, arrays and other NumPy objects are displayed.
【例】
import numpy as np
np.set_printoptions(precision=4)
x = np.array([1.123456789])
print(x) # [1.1235]
np.set_printoptions(threshold=20)
x = np.arange(50)
print(x) # [ 0 1 2 ... 47 48 49]
np.set_printoptions(threshold=np.iinfo(np.int).max)
print(x)
# [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
# 48 49]
eps = np.finfo(float).eps
x = np.arange(4.)
x = x ** 2 - (x + eps) ** 2
print(x)
# [-4.9304e-32 -4.4409e-16 0.0000e+00 0.0000e+00]
np.set_printoptions(suppress=True)
print(x) # [-0. -0. 0. 0.]
x = np.linspace(0, 10, 10)
print(x)
# [ 0. 1.1111 2.2222 3.3333 4.4444 5.5556 6.6667 7.7778 8.8889
# 10. ]
np.set_printoptions(precision=2, suppress=True, threshold=5)
print(x) # [ 0. 1.11 2.22 ... 7.78 8.89 10. ]
numpy.get_printoptions()
Return the current print options.
【例】
import numpy as np
x = np.get_printoptions()
print(x)
# {
# 'edgeitems': 3,
# 'threshold': 1000,
# 'floatmode': 'maxprec',
# 'precision': 8,
# 'suppress': False,
# 'linewidth': 75,
# 'nanstr': 'nan',
# 'infstr': 'inf',
# 'sign': '-',
# 'formatter': None,
# 'legacy': False
# }
當前活動
我是 終身學習者“老馬”,一個長期踐行“結伴式學習”理念的 中年大叔。
我崇尚分享,渴望成長,於2010年創立了“LSGO軟件技術團隊”,並加入了國內著名的開源組織“Datawhale”,也是“Dre@mtech”、“智能機器人研究中心”和“大數據與哲學社會科學實驗室”的一員。
願我們一起學習,一起進步,相互陪伴,共同成長。
後臺回覆「搜搜搜」,隨機獲取電子資源!
歡迎關注,請掃描二維碼: