前言
個人感覺網上對numpy的總結感覺不夠詳盡細致,在這里我對numpy做個相對細致的小結吧,在數據分析與人工智能方面會有所涉及到的東西在這里都說說吧,也是對自己學習的一種小結!
numpy用法的介紹
安裝部分我就不說了,裝個pip,使用命令pip install numpy就可以安裝了,在Ubuntu中可能會出現沒有權限的提示,直接加上sudo即可,以下講解都是建立在python3平台的講解,python2類似,python3中安裝的時候使用sudo pip3 install numpy即可。
首先,numpy是個求解數學矩陣,做矩陣計算
1.genfromtxt
numpy numpy.genfromtxt(""),這里我們講解下,genfromtxt函數的意思是讀取文件信息,用來處理數據信息,可以處理數據文件
舉個例子:
import numpy world_alcohol = numpy.genfromtxt("world_alcohol.txt",delimiter = ",",dtype = str) print(type(world_alcohol)) print(world_alcohol) print(help(numpy.genfromtxt))
打印結果如下:
<class 'numpy.ndarray'> [['Year' 'WHO region' 'Country' 'Beverage Types' 'Display Value'] ['1986' 'Western Pacific' 'Viet Nam' 'Wine' '0'] ['1986' 'Americas' 'Uruguay' 'Other' '0.5'] ..., ['1987' 'Africa' 'Malawi' 'Other' '0.75'] ['1989' 'Americas' 'Bahamas' 'Wine' '1.5'] ['1985' 'Africa' 'Malawi' 'Spirits' '0.31']] Help on function genfromtxt in module numpy.lib.npyio: genfromtxt(fname, dtype=<class '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=None, replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None) Load data from a text file, with missing values handled as specified. Each line past the first `skip_header` lines is split at the `delimiter` character, and characters following the `comments` character are discarded. Parameters ---------- fname : file, str, pathlib.Path, list of str, generator File, filename, list, or generator to read. If the filename extension is `.gz` or `.bz2`, the file is first decompressed. Note that generators must return byte strings in Python 3k. The strings in a list or produced by a generator are treated as lines. dtype : dtype, optional Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually. comments : str, optional The character used to indicate the start of a comment. All the characters occurring on a line after a comment are discarded delimiter : str, int, or sequence, optional The string used to separate values. By default, any consecutive whitespaces act as delimiter. An integer or sequence of integers can also be provided as width(s) of each field. -- More --
我解釋一下上面的用法,genfromtxt傳入了三個參數,第一個參數是數據文件,名為world_alcohol.txt,該數據文件有需要的同學可以加我好友私聊我,或者把你的請求發郵箱至i_love_sjtu@qq.com
然后delimiter是分隔符,由於數據集中的數據是用逗號分隔的,所以設定參數delimiter=',',dtype是獲取數據類型,數據集中的類型為str
print(type(world_alcohol))打印數據文件的數據類型
print(world_alcohol)打印數據集
print(help(numpy.genfromtxt))打印genfromtxt用法
加入skip_header,跳轉至以1開頭的數據
import numpy world_alcohol = numpy.genfromtxt("world_alcohol.txt",delimiter=",",dtype=str,skip_header=1) print(world_alcohol)
打印結果如下:
[['1986' 'Western Pacific' 'Viet Nam' 'Wine' '0'] ['1986' 'Americas' 'Uruguay' 'Other' '0.5'] ['1985' 'Africa' "Cte d'Ivoire" 'Wine' '1.62'] ..., ['1987' 'Africa' 'Malawi' 'Other' '0.75'] ['1989' 'Americas' 'Bahamas' 'Wine' '1.5'] ['1985' 'Africa' 'Malawi' 'Spirits' '0.31']]
2.shape
xxx.shape 顯示的功能是查看矩陣或者數組的維數
舉個例子:
import numpy vector = numpy.array([5,10,15,20]) matrix = numpy.array([[5,10,15],[20,25,30],[35,40,45]]) print(vector) print(matrix) print(vector.shape) print(matrix.shape)
打印結果如下:
[ 5 10 15 20] [[ 5 10 15] [20 25 30]] (4,) (2, 3) [Finished in 0.6s]
顯示出當前vector的維度是一維矩陣
matrix的維度是2行3列
3.索引
一維數組的索引:與Python的列表索引功能相似
先舉個例子:
import numpy world_alcohol = numpy.genfromtxt("world_alcohol.txt",delimiter=",",dtype=str,skip_header=1) uruguay_other_1986 = world_alcohol[1,4] third_country = world_alcohol[2,2] print(uruguay_other_1986) print(third_country)
打印結果如下:
0.5 Cte d'Ivoire
uruguay_other_1986取值的時候取的是第一個列表中的第四個值(從0開始算)
third_country取值的時候取的是第二個列表中的第二個值(從0開始算)
4.切片
舉例子:
import numpy vector = numpy.array([5,10,15,20]) print(vector[0:3])
打印結果如下:
[ 5 10 15]
這個和python中切片效果一樣,取的是左閉右開的界線
下一個例子:
import numpy matrix = numpy.array([[5,10,15],[20,25,30],[35,40,45]]) print(matrix[:,1])
打印結果如下:
[10 25 40]
:表示選取所有的行 逗號隔開 然后取列 取第一列(從0開始計算)
下一個例子:
import numpy matrix = numpy.array([[5,10,15],[20,25,30],[35,40,45]]) print(matrix[:,0:2])
打印結果如下:
[[ 5 10] [20 25] [35 40]]
這個意思是:表示選取所有的行 逗號隔開 然后取列 這里用到了切片 取的是從第零列開始到第二列(小於2) 實際上取的就是前兩列
下一個例子:
import numpy matrix = numpy.array([[5,10,15],[20,25,30],[35,40,45]]) print(matrix[1:3,0:2])
打印結果如下:
[[20 25]
[35 40]]
這個意思是我們選取的行是第一行到第三行(小於3) 這里用到了切片 然后取列 這也用到了切片 取的是從第零列開始到第二列(小於2) 實際上取的就是前兩列
5.布爾類型的相關判斷
舉個例子:
import numpy vector = numpy.array([5,10,15,20]) vector == 10
打印結果如下:
>>array([False, True, False, False], dtype=bool)
返回一個布爾型結果 判斷了該矩陣中是否有值等於10
== 相當於對矩陣中的每一個元素都進行了一個判斷
下一個例子:
import numpy matrix = numpy.array([[5,10,15],[20,25,30],[35,40,45]]) matrix == 25
打印結果如下:
array([[False, False, False],
[False, True, False],
[False, False, False]], dtype=bool)
解釋的原理和上述一樣
下一個例子:
import numpy vector = numpy.array([5,10,15,20]) equal_to_ten = (vector == 10) print(equal_to_ten) print(vector[equal_to_ten])
打印結果如下:
[False True False False]
[10]
意思是 vector == 10 直接對矩陣的值做了個判斷 把布爾類型的矩陣傳遞給equal_to_ten
然后的話打印結果為布爾類型的矩陣 這個布爾類型是一個索引 我們打印這個vector[布爾類型的索引]即可找回原值 返回真實值
下一個例子:
import numpy matrix = numpy.array([[5,10,15],[20,25,30],[35,40,45]]) second_conlumn_25 = (matrix[:,1] == 25) print(second_conlumn_25) print(matrix[second_conlumn_25, :])
打印結果如下:
[False True False]
[[20 25 30]]
意思是 :表示選取所有的行 逗號隔開 然后取列 取的是第一列(從0開始) 然后直接對這一列的值進行判斷 判斷這一列
中的元素是否等於25 並將其布爾類型的值傳遞給second_conlumn_25
然后打印出的second_conlumn_25的結果為一個布爾類型的列表
而把second_conlumn_25當作索引值 我們去尋找有25的這一行 逗號隔開 :表示直接選取這一行的數據 然后打印出來
下一個例子:
import numpy vector = numpy.array([5,10,15,20]) equal_to_ten_and_five = (vector == 10) & (vector == 5) print(equal_to_ten_and_five)
打印結果如下:
[False False False False]
意思是查找當前的這個矩陣中的數既等於10又等於5的數 顯然不存在 所以全部輸出False
下一個例子:
import numpy vector = numpy.array([5,10,15,20]) equal_to_ten_or_five = (vector == 10) | (vector == 5) print(equal_to_ten_or_five)
打印結果如下:
[ True True False False]
意思是查找當前的這個矩陣中的數等於10或者等於5的數 顯然不存在 所以輸出True True False False
6.dtype與astype
dtype 輸出的是矩陣中的數據類型
舉個例子:
import numpy vector = numpy.array([5,10,15,20]) print(vector.dtype)
打印結果如下:
int32
如果我們想轉換矩陣中的數據類型 我們應該使用astype進行轉換
舉個例子:
import numpy vector = vector.astype(float) print(vector.dtype)
打印結果如下:
float64
這樣就OK了!!!
7.min與max
min求解該矩陣中的最小值
舉個例子:
import numpy vector = numpy.array([5,10,15,20]) vector.min()
打印結果如下:
>>5
max求解該矩陣中的最大值
舉個例子:
import numpy vector = numpy.array([5,10,15,20]) vector.max()
打印結果如下:
>>20
8.sum
sum 可以指定了一個維度 對行或者列求和
舉個例子:
import numpy matrix = numpy.array([[5,10,15],[20,25,30],[35,40,45]]) matrix.sum(axis=1)
打印結果如下:
>>array([ 30, 75, 120])
指定了一個維度 對行求和
下個例子:
import numpy matrix = numpy.array([[5,10,15],[20,25,30],[35,40,45]]) matrix.sum(axis=0)
打印結果如下:
>>array([60, 75, 90])
指定了一個維度 axis = 0 行號為0 相當於對列求和
9.reshape
reshape給數組一個新的形狀而不改變其數據
舉個例子:
import numpy as np print(np.arange(15)) a = np.arange(15).reshape(3,5) print(a)
打印結果如下:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14] [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14]]
np是指定了numpy的別名,np.arange依次造出十五個元素 變成了一個向量的形式,reshape函數表明,我們要生成一個3行5列這樣的矩陣
此時我們輸入如下語句:
print(a.shape)
將會打印出如下結果:
(3, 5)
10.ndim
ndim中的dim是英文dimension維度的縮寫,表示打印出矩陣的維度
舉個例子:
import numpy as np a = np.arange(15).reshape(3,5) print(a.ndim)
打印結果如下:
>>2
打印出當前矩陣的維度為2
11.size
size打印出矩陣的元素個數
舉個例子:
import numpy a = np.arange(15).reshape(3,5) print(a.size)
打印結果如下:
>>15
12.zeros
初始化一個矩陣,可以傳入參數行和列,生成一個零矩陣
舉個例子:
import numpy as np np.zeros((3,4))
打印結果如下:
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
初始化一個矩陣,生成一個三行四列的零矩陣
13.ones
初始化一個矩陣,可以傳入參數行和列,還可以傳入數據類型dtype
舉個例子:
import numpy as np np.ones((2,3,4),dtype=np.int32)
打印結果如下:
array([[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]])
構造出一個三維矩陣 矩陣中的元素均為1 然后我們用dtype指定元素類型為int32
14.arange
arange通過定義起點 終點 步長 然后我們構造出了一個數組 右邊界不可以取等號,取的是左閉右開區間
舉個例子:
import numpy as np np.arange(10,30,5)
打印結果如下:
array([10, 15, 20, 25])
15.random
random構造出一個矩陣 產生的值默認在-1-1之間
舉個例子:
import numpy as np np.random.random((2,3))
打印結果如下:
array([[ 0.77296788, 0.00748236, 0.59905565],
[ 0.05577331, 0.08520327, 0.58034632]])
16.linspace
舉個例子:
from numpy import pi np.linspace(0,2*pi,100)
打印結果如下:
array([ 0. , 0.06346652, 0.12693304, 0.19039955, 0.25386607, 0.31733259, 0.38079911, 0.44426563, 0.50773215, 0.57119866, 0.63466518, 0.6981317 , 0.76159822, 0.82506474, 0.88853126, 0.95199777, 1.01546429, 1.07893081, 1.14239733, 1.20586385, 1.26933037, 1.33279688, 1.3962634 , 1.45972992, 1.52319644, 1.58666296, 1.65012947, 1.71359599, 1.77706251, 1.84052903, 1.90399555, 1.96746207, 2.03092858, 2.0943951 , 2.15786162, 2.22132814, 2.28479466, 2.34826118, 2.41172769, 2.47519421, 2.53866073, 2.60212725, 2.66559377, 2.72906028, 2.7925268 , 2.85599332, 2.91945984, 2.98292636, 3.04639288, 3.10985939, 3.17332591, 3.23679243, 3.30025895, 3.36372547, 3.42719199, 3.4906585 , 3.55412502, 3.61759154, 3.68105806, 3.74452458, 3.8079911 , 3.87145761, 3.93492413, 3.99839065, 4.06185717, 4.12532369, 4.1887902 , 4.25225672, 4.31572324, 4.37918976, 4.44265628, 4.5061228 , 4.56958931, 4.63305583, 4.69652235, 4.75998887, 4.82345539, 4.88692191, 4.95038842, 5.01385494, 5.07732146, 5.14078798, 5.2042545 , 5.26772102, 5.33118753, 5.39465405, 5.45812057, 5.52158709, 5.58505361, 5.64852012, 5.71198664, 5.77545316, 5.83891968, 5.9023862 , 5.96585272, 6.02931923, 6.09278575, 6.15625227, 6.21971879, 6.28318531])
指定一個區間 我們要生成100個數 指定了一個值 起點值為0 終點值為2*pi
linspace意思就是在區間里面造出100個值 這100個值間隔是平均的
再舉一個例子:
from numpy import pi np.sin(np.linspace(0,2*pi,100))
打印結果如下:
array([ 0.00000000e+00, 6.34239197e-02, 1.26592454e-01, 1.89251244e-01, 2.51147987e-01, 3.12033446e-01, 3.71662456e-01, 4.29794912e-01, 4.86196736e-01, 5.40640817e-01, 5.92907929e-01, 6.42787610e-01, 6.90079011e-01, 7.34591709e-01, 7.76146464e-01, 8.14575952e-01, 8.49725430e-01, 8.81453363e-01, 9.09631995e-01, 9.34147860e-01, 9.54902241e-01, 9.71811568e-01, 9.84807753e-01, 9.93838464e-01, 9.98867339e-01, 9.99874128e-01, 9.96854776e-01, 9.89821442e-01, 9.78802446e-01, 9.63842159e-01, 9.45000819e-01, 9.22354294e-01, 8.95993774e-01, 8.66025404e-01, 8.32569855e-01, 7.95761841e-01, 7.55749574e-01, 7.12694171e-01, 6.66769001e-01, 6.18158986e-01, 5.67059864e-01, 5.13677392e-01, 4.58226522e-01, 4.00930535e-01, 3.42020143e-01, 2.81732557e-01, 2.20310533e-01, 1.58001396e-01, 9.50560433e-02, 3.17279335e-02, -3.17279335e-02, -9.50560433e-02, -1.58001396e-01, -2.20310533e-01, -2.81732557e-01, -3.42020143e-01, -4.00930535e-01, -4.58226522e-01, -5.13677392e-01, -5.67059864e-01, -6.18158986e-01, -6.66769001e-01, -7.12694171e-01, -7.55749574e-01, -7.95761841e-01, -8.32569855e-01, -8.66025404e-01, -8.95993774e-01, -9.22354294e-01, -9.45000819e-01, -9.63842159e-01, -9.78802446e-01, -9.89821442e-01, -9.96854776e-01, -9.99874128e-01, -9.98867339e-01, -9.93838464e-01, -9.84807753e-01, -9.71811568e-01, -9.54902241e-01, -9.34147860e-01, -9.09631995e-01, -8.81453363e-01, -8.49725430e-01, -8.14575952e-01, -7.76146464e-01, -7.34591709e-01, -6.90079011e-01, -6.42787610e-01, -5.92907929e-01, -5.40640817e-01, -4.86196736e-01, -4.29794912e-01, -3.71662456e-01, -3.12033446e-01, -2.51147987e-01, -1.89251244e-01, -1.26592454e-01, -6.34239197e-02, -2.44929360e-16])
指定一個區間 我們要生成100個數 指定了一個值 起點值為0 終點值為2*pi
linspace意思就是在區間里面造出100個值 這100個值間隔是平均的 然后最后我們對這個值取正弦即可
17.floor與ravel
舉個例子:
import numpy as np a = np.floor(10*np.random.random((3,4))) print(a) print('------') print(a.ravel()) print('------') a.shape = (6,2) print(a) print('------') print(a.T)
打印結果如下:
[[ 4. 9. 0. 4.] [ 8. 5. 4. 9.] [ 1. 9. 2. 6.]] ------ [ 4. 9. 0. 4. 8. 5. 4. 9. 1. 9. 2. 6.] ------ [[ 4. 9.] [ 0. 4.] [ 8. 5.] [ 4. 9.] [ 1. 9.] [ 2. 6.]] ------ [[ 4. 0. 8. 4. 1. 2.] [ 9. 4. 5. 9. 9. 6.]]
random.random((3,4))是建立一個3行4列的一個區間范圍在-1~1的矩陣
然后我們如果覺得值太小了 就可以在np這里*10 floor操作是向下取整
ravel 是將一個矩陣拉平成一個向量 即用向量的形式表示這個矩陣
而a.shape(6,2)又將一個向量轉換為一個6*2的矩陣
a.T表示求矩陣a的一個轉置矩陣 行和列進行變換
如果一個向量中的元素個數已知 我們已經確定了其中的行數或者列數 其實此時另外一個數已經默認確定了 我們不想去計算那個列數或者行數
是多少時 我們應該怎么辦呢 我們如果已經確定了其中的行數或者列數 我們只需要在另外一個位置寫上-1就好了 此時計算機會自動幫你計算好這個值
18.hstack與vstack
np.hstack((a,b)) 將a矩陣和b矩陣進行橫向拼接
np.vstack((a,b))將a矩陣和b矩陣進行縱向拼接
舉個例子:
import numpy as np a = np.floor(10*np.random.random((2,12))) print(a) print('------') print(np.hsplit(a,3)) print('------') print(np.hsplit(a,(3,4))) a = np.floor(10*np.random.random((12,2))) print('------') print(a) np.vsplit(a,3)
打印結果如下:
[[ 5. 1. 3. 4. 6. 5. 4. 5. 4. 8. 2. 2.] [ 4. 9. 2. 6. 8. 9. 5. 9. 6. 5. 5. 7.]] ------ [array([[ 5., 1., 3., 4.], [ 4., 9., 2., 6.]]), array([[ 6., 5., 4., 5.], [ 8., 9., 5., 9.]]), array([[ 4., 8., 2., 2.], [ 6., 5., 5., 7.]])] ------ [array([[ 5., 1., 3.], [ 4., 9., 2.]]), array([[ 4.], [ 6.]]), array([[ 6., 5., 4., 5., 4., 8., 2., 2.], [ 8., 9., 5., 9., 6., 5., 5., 7.]])] ------ [[ 1. 8.] [ 7. 4.] [ 0. 5.] [ 9. 1.] [ 6. 5.] [ 4. 5.] [ 1. 2.] [ 0. 1.] [ 3. 6.] [ 2. 7.] [ 7. 8.] [ 7. 6.]] [array([[ 1., 8.], [ 7., 4.], [ 0., 5.], [ 9., 1.]]), array([[ 6., 5.], [ 4., 5.], [ 1., 2.], [ 0., 1.]]), array([[ 3., 6.], [ 2., 7.], [ 7., 8.], [ 7., 6.]])]
hsplit是對行進行切分 a表示待切分的行參數 3表示切分成三份
np.hsplit(a,(3,4)) 傳入元組 指定位置進行切割
vsplit是對列進行切分 a表示待切分的行參數 3表示切分成三份
19.view與copy
view是淺復制
舉個例子:
import numpy as np a = np.arange(12) b = a print(b is a) b.shape = 3,4 print(a.shape) print(id(a)) print(id(b))
打印結果如下:
True (3, 4) 3144967327792 3144967327792
我們可以發現a與b的地址是相同的,這個就是所謂的深復制
讓我再看看下面這個例子:
import numpy a = np.arange(12) c = a.view() print(c is a) c.shape = 2,6 print(a.shape) c[0,4] = 1234 print(a) print(id(a)) print(id(c))
打印結果如下:
False (12,) [ 0 1 2 3 1234 5 6 7 8 9 10 11] 2391025174608 2391025175008
我們可以看出淺復制不會復制a的地址到c,改變c的值不會影響到a
再看下一個寫法:
import numpy as np a = np.arange(12) d = a.copy() d is a
打印結果如下:
False
從結果我們可以看出,copy也是屬於淺拷貝
20.argmax
argmax 索引最大值的位置
舉個例子:
import numpy as np data = np.sin(np.arange(20)).reshape(5,4) print(data) ind = data.argmax(axis=0) print(ind) data_max = data[ind,range(data.shape[1])] print(data_max)
打印結果如下:
[[ 0. 0.84147098 0.90929743 0.14112001] [-0.7568025 -0.95892427 -0.2794155 0.6569866 ] [ 0.98935825 0.41211849 -0.54402111 -0.99999021] [-0.53657292 0.42016704 0.99060736 0.65028784] [-0.28790332 -0.96139749 -0.75098725 0.14987721]] [2 0 3 1] [ 0.98935825 0.84147098 0.99060736 0.6569866 ]
argmax 索引最大值的位置
data.argmax(axis=0) axis=0意思是指定列去索引 找出最大值返回索引值的位置
21.tile
tile 對當前的行和列進行擴展
舉個例子:
import numpy as np a = np.arange(0,40,10) print(a) b = np.tile(a,(3,5)) print(b)
打印結果如下:
[ 0 10 20 30] [[ 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30] [ 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30] [ 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30 0 10 20 30]]
我們可以看出,矩陣由原來的一維擴展到了三行五列
22.sort與argsort
sort 對當前的數組按照行的維度進行排序(因為axis=1)
argsort 是對值的索引進行排序 默認是值從小到大 然后按照值排序獲取索引 輸出索引
舉個例子:
import numpy as np a = np.array([[4,3,5],[1,2,4]]) print(a) print('------') b = np.sort(a,axis=1) print(b) a.sort(axis=1) print('------') print(a) a = np.array([4,3,1,2]) j = np.argsort(a) print('------') print(j) print('------') print(a[j])
打印結果如下:
[[4 3 5] [1 2 4]] ------ [[3 4 5] [1 2 4]] ------ [[3 4 5] [1 2 4]] ------ [2 3 1 0] ------ [1 2 3 4]
以上是我在運用中所用到的一些函數及用法,歡迎大家指正批評,如果有需要改進的地方,還希望不吝賜教,如果覺得本文對你有用,別忘記關注訂閱推薦博主,謝謝大家的支持!!!