前言:學(xué)習(xí)數(shù)據(jù)分析在我們有了Python基礎(chǔ)之后炉抒,我們需要對(duì)數(shù)據(jù)進(jìn)行處理,創(chuàng)建數(shù)據(jù)稚叹、訪問數(shù)據(jù)焰薄、做數(shù)據(jù)運(yùn)算等。所以需要我們先學(xué)習(xí)Numpy第三方庫(kù)扒袖,所以需要我們?cè)诃h(huán)境裝安裝pip install numpy
塞茅。
此行替換為```即可
一、Numpy概述
numpy(Numerical Python)提供了python對(duì)多維數(shù)組對(duì)象的支持:ndarray
僚稿,具有矢量運(yùn)算能力凡桥,快速、節(jié)省空間蚀同。numpy支持高級(jí)大量的維度數(shù)組與矩陣運(yùn)算缅刽,此外也針對(duì)數(shù)組運(yùn)算提供大量的數(shù)學(xué)函數(shù)庫(kù)啊掏。
二、Ndarray對(duì)象
最重要的一個(gè)特點(diǎn)是其 N 維數(shù)組對(duì)象 ndarray
衰猛,它是一系列同類型數(shù)據(jù)的集合迟蜜,以 0 下標(biāo)為開始進(jìn)行集合中元素的索引。
創(chuàng)建一個(gè) ndarray 只需調(diào)用 NumPy 的 array
函數(shù)即可:
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
實(shí)例:
import numpy as np
print('一維數(shù)組的創(chuàng)建')
a = np.array([1,2,3])
print (a)
print('多維數(shù)據(jù)的創(chuàng)建')
b = np.array([[1, 2], [3, 4]])
print (b)
print('最小維度參數(shù)ndmin')
c = np.array([1, 2, 3,4,5], ndmin = 2)
print (c)
print('dtype 參數(shù)')
d = np.array([1, 2, 3], dtype = complex)
print (d)
結(jié)果:
三啡省、NumPy 數(shù)組屬性
本節(jié)我們將來了解 NumPy 數(shù)組的一些基本屬性娜睛。
實(shí)例:
a = np.arange(12)
print (a.ndim,'打印出a的維度 現(xiàn)只有一個(gè)維度')
print(a)
# 現(xiàn)在調(diào)整其大小
b = a.reshape(2,2,3)
print(b)
print (b.ndim,'打印出b的維度 現(xiàn)在擁有三個(gè)維度')
結(jié)果:
實(shí)例:
a = np.array([[1,2,3],[4,5,6]])
print (a.shape,'打印出數(shù)組的維度行,列數(shù)')
b = a.reshape(3,2) #調(diào)整數(shù)組大小
print(b,'調(diào)整后的結(jié)果',b.shape)
c = b.size #得到數(shù)組元素總個(gè)數(shù)
print(c)
結(jié)果:
四卦睹、NumPy 創(chuàng)建數(shù)組
在第二節(jié)我們講了ndarray 數(shù)組除了可以使用array()
構(gòu)造器來創(chuàng)建外
numpy.empty
方法用來創(chuàng)建一個(gè)指定形狀(shape)畦戒、數(shù)據(jù)類型(dtype)且未初始化的數(shù)組:
numpy.empty(shape, dtype = float, order = 'C')
實(shí)例:
import numpy as np
x = np.empty([3,2], dtype = int)
print (x)
結(jié)果:
numpy.zeros()
創(chuàng)建指定大小的數(shù)組,數(shù)組元素以 0 來填充:
numpy.zeros(shape, dtype = float, order = 'C')
實(shí)例:
import numpy as np
# 默認(rèn)為浮點(diǎn)數(shù)
x = np.zeros(5)
print(x,'x的結(jié)果')
# 設(shè)置類型為整數(shù)
y = np.zeros((5,), dtype = np.int)
print(y,'y的結(jié)果')
# 自定義類型
z = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])
print(z,'z的結(jié)果')
結(jié)果:
numpy.ones()
創(chuàng)建指定形狀的數(shù)組结序,數(shù)組元素以 1 來填充:
numpy.ones(shape, dtype = None, order = 'C')
實(shí)例:
import numpy as np
# 默認(rèn)為浮點(diǎn)數(shù)
x = np.ones(5)
print(x,'x的結(jié)果')
# 自定義類型
y = np.ones([2,2], dtype = int)
print(y,'y的結(jié)果')
結(jié)果:
接下來是NumPy 從數(shù)值范圍創(chuàng)建數(shù)組
numpy.arange()
numpy 包中的使用 arange
函數(shù)創(chuàng)建數(shù)值范圍并返回 ndarray 對(duì)象障斋,函數(shù)格式如下:
numpy.arange(start, stop, step, dtype)
實(shí)例:
import numpy as np
#x數(shù)組生成1到5的數(shù)組
x = np.arange(5)
#y數(shù)組設(shè)置了起始值、終止值及步長(zhǎng):
y = np.arange(10,20,2)
print (x,'x的數(shù)組')
print (y,'y的數(shù)組')
結(jié)果:
numpy.linspace()
numpy.linspace
函數(shù)用于創(chuàng)建一個(gè)一維數(shù)組徐鹤,數(shù)組是一個(gè)等差數(shù)列構(gòu)成的垃环,格式如下:
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
實(shí)例:
import numpy as np
#x用到三個(gè)參數(shù),設(shè)置起始點(diǎn)為 1 返敬,終止點(diǎn)為 10遂庄,數(shù)列個(gè)數(shù)為 10。
x = np.linspace(1,10,10)
print(x,'x的值')
#y設(shè)置全部是1的等差數(shù)列
y = np.linspace(1,1,10)
print(y,'y的值')
#z不包含終止值20
z = np.linspace(10,20,5,endpoint = False)
print(z,'z的值')
結(jié)果:
五劲赠、NumPy值的訪問(切片和索引)
- 對(duì)象的內(nèi)容可以通過索引或切片來訪問和修改涛目,與 Python 中 list 的切片操作一樣。
- ndarray 數(shù)組可以基于
0 - n
的下標(biāo)進(jìn)行索引经磅,切片對(duì)象可以通過內(nèi)置的slice
函數(shù)泌绣,并設(shè)置start, stop 及 step
參數(shù)進(jìn)行,從原數(shù)組中切割出一個(gè)新數(shù)組预厌。
實(shí)例:
import numpy as np
#我們通過冒號(hào)分隔切片參數(shù)和python列表一樣 start:stop:step 來進(jìn)行切片操作
a = np.arange(10)
b = a[2:7:2] # 從索引 2 開始到索引 7 停止阿迈,間隔為 2
print(b,'b的值')
#多維數(shù)組同樣適應(yīng)索引和切片操作
c = np.array([[1,2,3],[3,4,5],[4,5,6]])
print(c,'c的值')
# 從某個(gè)索引處開始切割
print('從數(shù)組索引 a[1:] 處開始切割')
print(c[1:],'c切片的值')
結(jié)果:
實(shí)例:
import numpy as np
a = np.array([[1,2,3], [4,5,6],[7,8,9]])
b = a[1:3, 1:3]
print(b)
結(jié)果:
六、NumPy 數(shù)組運(yùn)算
如果兩個(gè)數(shù)組 a 和 b 形狀相同轧叽,即滿足 a.shape == b.shape苗沧,那么 a*b 的結(jié)果就是 a 與 b 數(shù)組對(duì)應(yīng)位相乘。這要求維數(shù)相同炭晒,且各維度的長(zhǎng)度相同待逞。
實(shí)例:
import numpy as np
a = np.array([1,2,3,4])
b = np.array([10,20,30,40])
c = a * b
print (c)
結(jié)果:
- 總結(jié):數(shù)組的簡(jiǎn)單加減乘除運(yùn)算滿足 a.shape == b.shape,那么 a*b 的結(jié)果就是 a 與 b 數(shù)組對(duì)應(yīng)位相乘网严。這要求維數(shù)相同识樱,且各維度的長(zhǎng)度相同。
七、NumPy IO
- Numpy 可以讀寫磁盤上的文本數(shù)據(jù)或二進(jìn)制數(shù)據(jù)怜庸。
- NumPy 為 ndarray 對(duì)象引入了一個(gè)簡(jiǎn)單的文件格式:npy当犯。
- npy 文件用于存儲(chǔ)重建 ndarray 所需的數(shù)據(jù)、圖形割疾、dtype 和其他信息嚎卫。
常用的 IO 函數(shù)有:
load() 和 save() 函數(shù)是讀寫文件數(shù)組數(shù)據(jù)的兩個(gè)主要函數(shù),默認(rèn)情況下宏榕,數(shù)組是以未壓縮的原始二進(jìn)制格式保存在擴(kuò)展名為 .npy 的文件中拓诸。
savze() 函數(shù)用于將多個(gè)數(shù)組寫入文件,默認(rèn)情況下麻昼,數(shù)組是以未壓縮的原始二 進(jìn)制格式保存在擴(kuò)展名為 .npz 的文件中奠支。
loadtxt() 和 savetxt() 函數(shù)處理正常的文本文件(.txt 等)
numpy.save()
numpy.save()
函數(shù)將數(shù)組保存到以.npy
為擴(kuò)展名的文件中。
numpy.save(file, arr, allow_pickle=True, fix_imports=True)
實(shí)例:
import numpy as np
a = np.array([1,2,3,4,5])
# 保存到 outfile.npy 文件上
np.save('outfile.npy',a)
# 保存到 outfile2.npy 文件上抚芦,如果文件路徑?jīng)]有擴(kuò)展名 .npy胚宦,該擴(kuò)展名會(huì)被自動(dòng)加上
np.save('outfile2',a)
- 查看時(shí)是亂碼,因?yàn)樗鼈兪?Numpy 專用的二進(jìn)制格式后的數(shù)據(jù)燕垃。我們可以使用 load() 函數(shù)來讀取數(shù)據(jù)就可以正常顯示了:
實(shí)例:
import numpy as np
b = np.load('outfile.npy')
print (b)
np.savez()
numpy.savez()
函數(shù)將多個(gè)數(shù)組保存到以npz
為擴(kuò)展名的文件中。
numpy.savez(file, *args, **kwds)
實(shí)例:
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.arange(0, 1.0, 0.1)
c = np.sin(b)
# c 使用了關(guān)鍵字參數(shù) sin_array
np.savez("runoob.npz", a, b, sin_array = c)
r = np.load("runoob.npz")
print(r.files) # 查看各個(gè)數(shù)組名稱
print(r["arr_0"]) # 數(shù)組 a
print(r["arr_1"]) # 數(shù)組 b
print(r["sin_array"]) # 數(shù)組 c
結(jié)果:
savetxt()
savetxt()
函數(shù)是以簡(jiǎn)單的文本文件格式存儲(chǔ)數(shù)據(jù)井联,對(duì)應(yīng)的使用 loadtxt()
函數(shù)來獲取數(shù)據(jù)卜壕。
np.savetxt(FILENAME, a, fmt="%d", delimiter=",")
np.loadtxt(FILENAME, dtype=int, delimiter=' ')
- 參數(shù)
delimiter
可以指定各種分隔符、針對(duì)特定列的轉(zhuǎn)換器函數(shù)烙常、需要跳過的行數(shù)等轴捎。
實(shí)例:
mport numpy as np
a = np.array([1,2,3,4,5])
np.savetxt('out.txt',a)
b = np.loadtxt('out.txt')
print(b)
結(jié)果:
使用 delimiter 參數(shù)實(shí)例:
import numpy as np
a=np.arange(0,10,0.5).reshape(4,-1)
np.savetxt("out.txt",a,fmt="%d",delimiter=",") # 改為保存為整數(shù),以逗號(hào)分隔
b = np.loadtxt("out.txt",delimiter=",") # load 時(shí)也要指定為逗號(hào)分隔
print(b)
結(jié)果: