日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

Python數(shù)據(jù)分析丨numpy基本操作,了解一下?

 quanshan 2019-01-22

一個栗子

復(fù)制代碼
 1 >>>import numpy as np
 2 
 3 >>>a = np.arange(15).reshape(3, 5)
 4 
 5 >>>a
 6 
 7 array([[ 0,    1,    2,    3,    4],
 8 
 9 [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])
10 >>>a.shape
11 
12 (3, 5)
13 
14 >>>a.ndim  # 數(shù)組軸的個數(shù),在python的世界中,軸的個數(shù)被稱作秩
15 
16 2
17 
18 >>>a.dtype.name
19 
20 'int64'
21 
22 >>>a.itemsize  # 數(shù)組中每個元素的字節(jié)大小。
23 
24 8
25 
26 >>>a.size
27 
28 15
29 
30 >>>type(a)
31 
32 <type 'numpy.ndarray'>
33 
34 >>>b = np.array([6, 7, 8])
35 
36 >>>b
37 
38 array([6, 7, 8])
39 
40 >>>type(b)
41 
42 <type 'numpy.ndarray'>
復(fù)制代碼

基本數(shù)據(jù)類型

Numpy 常見的基本數(shù)據(jù)類型如下:

以上這些數(shù)據(jù)類型都可以通過 np.bool_ 、 np.float32 等方式訪問。

這些類型都可以在創(chuàng)建 ndarray 時通過參數(shù) dtype 來指定。

類型轉(zhuǎn)換

要轉(zhuǎn)換數(shù)組的類型,請使用.astype()方法(首選)或類型本身作為函數(shù)。

復(fù)制代碼
 1 >>>a
 2 
 3 array([ 0.,    1.,    2.])
 4 
 5 >>>a.astype(np.bool_)
 6 
 7 array([False,    True,    True], dtype=bool)
 8 
 9 >>>np.bool_(a)
10 
11 array([False,    True,    True], dtype=bool)
復(fù)制代碼

創(chuàng)建矩陣(采用ndarray對象)

對于Python中的numpy模塊,一般用其提供的ndarray對象。創(chuàng)建一個ndarray對象很簡單,只要將一個list作為參數(shù)即可。例如:

復(fù)制代碼
 1 >>>import numpy as np
 2 
 3 #創(chuàng)建一維的narray對象
 4 
 5 >>>a = np.array([2,3,4])
 6 
 7 >>>a
 8 
 9 array([2, 3, 4])
10 
11 >>>a.dtype dtype('int64')
12 # 浮點類型
13 
14 >>>b = np.array([1.2, 3.5, 5.1])
15 
16 >>>b.dtype
17 
18 dtype('float64')
19 
20 #創(chuàng)建二維的narray對象
21 
22 >>>a2 = np.array([[1,2,3,4,5],[6,7,8,9,10]])
23 
24 >>>b = np.array([(1.5,2,3), (4,5,6)])  # 使用的是元組
25 
26 >>>b
27 
28 array([[ 1.5,    2. ,    3. ],
29 
30 [4. ,  5. ,  6. ]])
31 
32 #The type of the array can also be explicitly specified at creation time:
33 
34 >>> c = np.array( [ [1,2], [3,4] ], dtype=complex )
35 
36 >>> c
37 
38 array([[ 1.+0.j,  2.+0.j],
39 
40 [3.+0.j,  4.+0.j]])
復(fù)制代碼

矩陣行數(shù)列數(shù)(二維情況)

復(fù)制代碼
1 import numpy as np
2 
3 a = np.array([[1,2,3,4,5],[6,7,8,9,10]])
4 
5 print(a.shape) #結(jié)果返回一個tuple元組 (2, 5) 2行,5列 print(a.shape[0]) #獲得行數(shù),返回 2 print(a.shape[1]) #獲得列數(shù),返回 5
復(fù)制代碼

矩陣的截取

按行列截取

矩陣的截取和list相同,可以通過[ ](方括號)來截取

復(fù)制代碼
1 import numpy as np
2 
3 a = np.array([[1,2,3,4,5],[6,7,8,9,10]])
4 
5 print(a[0:1]) #截取第一行,返回 [[1 2 3 4 5]]
6 
7 print(a[1,2:5]) #截取第二行,第三、四、五列,返回 [8 9 10]
8 
9 print(a[1,:]) #截取第二行,返回 [ 6    7    8    9 10]
復(fù)制代碼

按條件截取

復(fù)制代碼
 1 import numpy as np
 2 
 3 a = np.array([[1,2,3,4,5],[6,7,8,9,10]])
 4 
 5 b = a[a>6] # 截取矩陣a中大于6的元素,返回的是一維數(shù)組 print(b) # 返回 [ 7 8 9 10]
 6 
 7 #其實布爾語句首先生成一個布爾矩陣,將布爾矩陣傳入[](方括號)實現(xiàn)截取 print(a>6)
 8 
 9 #返回
10 
11 [[False False False False False]
12 
13 [False    True    True    True    True]]
復(fù)制代碼

按條件截取應(yīng)用較多的是對矩陣中滿足一定條件的元素變成特定的值。 例如將矩陣中大于6的元素變成0。

 

import numpy as np

a = np.array([[1,2,3,4,5],[6,7,8,9,10]])

print(a)

#開始矩陣為

[[ 1 2 3 4 5]

[6 7 8 9 10]]

>>>a[a>6] = 0

print(a)

#大于6清零后矩陣為

[[1 2 3 4 5]

[6 0 0 0 0]]

>>>y

array([[ 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]])
>>>b = y > 20

>>>y[b]

array([21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34])

Stacking together di?erent arrays


矩陣的合并可以通過numpy中的hstack方法和vstack方法實現(xiàn):


>>>a = np.floor(10*np.random.random((2,2)))

>>>a

array([[ 8., 8.],

[0., 0.]])

>>>b = np.floor(10*np.random.random((2,2)))

>>>b

array([[ 1., 8.],

[0., 4.]])

>>>np.vstack((a,b)) array([[ 8., 8.],

[0., 0.],

[1., 8.],

[0., 4.]])

>>>np.hstack((a,b))

array([[ 8., 8., 1., 8.],

[ 0., 0., 0., 4.]])

矩陣的合并也可以通過concatenate方法。

np.concatenate( (a1,a2), axis=0 ) 等價于 np.vstack( (a1,a2) )


np.concatenate( (a1,a2), axis=1 ) 等價于 np.hstack( (a1,a2) )


通過函數(shù)創(chuàng)建矩陣


arange

 

import numpy as np

a = np.arange(10) # 默認(rèn)從0開始到10(不包括10),步長為1 print(a) # 返回 [0 1 2 3 4 5 6 7 8 9]

a1 = np.arange(5,10) # 從5開始到10(不包括10),步長為1 print(a1) # 返回 [5 6 7 8 9]

a2 = np.arange(5,20,2) # 從5開始到20(不包括20),步長為2 print(a2) # 返回 [ 5 7 9 11 13 15 17 19]

linspace / logspace

 

import numpy as np

# 類似于matlab

a = np.linspace(0,10,7) # 生成首位是0,末位是10,含7個數(shù)的等差數(shù)列 print(a)

#結(jié)果

[ 0. 1.66666667 3.33333333 5. 6.66666667 8.33333333 10. ]

>>>a = np.ones(3, dtype=np.int32) # 范圍在‐2147483648‐‐‐2147483647

>>>b = np.linspace(0,pi,3)

>>>b.dtype.name

'float64'

>>>c = a+b

>>>c

array([ 1. , 2.57079633, 4.14159265])

>>>c.dtype.name 'float64'
>>>d = np.exp(c*1j)

>>>d

array([ 0.54030231+0.84147098j, ‐0.84147098+0.54030231j, ‐0.54030231‐0.84147098j])
>>>d.dtype.name 'complex128'

ones、zeros、eye、empty


ones創(chuàng)建全1矩陣 ,zeros創(chuàng)建全0矩陣 ,eye創(chuàng)建單位矩陣 ,empty創(chuàng)建空矩陣(實際有值)

import numpy as np

a_ones = np.ones((3,4)) # 創(chuàng)建3*4的全1矩陣

print(a_ones)

#結(jié)果

[[ 1. 1. 1. 1.]

[1. 1. 1. 1.]

[1. 1. 1. 1.]]

>>> np.ones((2,3,4), dtype=np.int16 ) # dtype can also be specified 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]]], dtype=int16) # Int16在‐32768 到 +32767之間

a_zeros = np.zeros((3,4)) # 創(chuàng)建3*4的全0矩陣

print(a_zeros)

#結(jié)果

[[ 0. 0. 0. 0.]

[0. 0. 0. 0.]

[0. 0. 0. 0.]]

a_eye = np.eye(3) # 創(chuàng)建3階單位矩陣

print(a_eye)

#結(jié)果

[[ 1. 0. 0.]

[0. 1. 0.]

[0. 0. 1.]]

a_empty = np.empty((3,4)) # 創(chuàng)建3*4的空矩陣

print(a_empty)

#結(jié)果

[[ 1.78006111e‐306 ‐3.13259416e‐294 4.71524461e‐309 1.94927842e+289]
[ 2.10230387e‐309 5.42870216e+294 6.73606381e‐310 3.82265219e‐297]
[ 6.24242356e‐309 1.07034394e‐296 2.12687797e+183 6.88703165e‐315]]

#有些矩陣太大,如果不想省略中間部分,通過set_printoptions來強制NumPy打印所有數(shù)據(jù)。

>>> np.set_printoptions(threshold='nan')

fromstring

fromstring()方法可以將字符串轉(zhuǎn)化成ndarray對象,需要將字符串?dāng)?shù)字化時這個方法比較有用,可以獲得字符串的ascii碼序列。


import numpy as np

a = "abcdef"

b = np.fromstring(a,dtype=np.int8) # 因為一個字符為8位,所以指定dtype為np.int8

#一個字母(例如:a、#、!之類的)用了1個字節(jié)來存儲,1byte 即8位. print(b) # 返回 [ 97 98 99 100 101 102]

random

 

>>>a = np.random.random((2,3)) # 產(chǎn)生2行,3列的隨機矩陣

>>>a

array([[ 0.18626021, 0.34556073, 0.39676747],

[0.53881673, 0.41919451, 0.6852195 ]])

fromfunction

fromfunction()方法可以根據(jù)矩陣的行號列號生成矩陣的元素。 例如創(chuàng)建一個矩陣,矩陣中的每個元素都為行號和列號的和。


import numpy as np

def func(i,j):

return i+j

a = np.fromfunction(func,(5,6))

#第一個參數(shù)為指定函數(shù),第二個參數(shù)為列表list或元組tuple,說明矩陣的大小 print(a)

#返回

[[ 0. 1. 2. 3. 4. 5.]

[1. 2. 3. 4. 5. 6.]

[2. 3. 4. 5. 6. 7.]

[3. 4. 5. 6. 7. 8.]

[4. 5. 6. 7. 8. 9.]]

#注意這里行號的列號都是從0開始的

矩陣的運算


常用矩陣運算符

Numpy中的ndarray對象重載了許多運算符,使用這些運算符可以完成矩陣間對應(yīng)元素的運算。

運算符 說明

+ 矩陣對應(yīng)元素相加

- 矩陣對應(yīng)元素相減

* 矩陣對應(yīng)元素相乘

/ 矩陣對應(yīng)元素相除,如果都是整數(shù)則取商

% 矩陣對應(yīng)元素相除后取余數(shù)

** 矩陣每個元素都取n次方,如**2:每個元素都取平方

 

 

import numpy as np

a1 = np.array([[4,5,6],[1,2,3]])

a2 = np.array([[6,5,4],[3,2,1]])

print(a1+a2) # 相加

#結(jié)果

[[10 10 10]

[4 4 4]]

print(a1/a2) # 整數(shù)相除取商

#結(jié)果

[[0 1 1] [0 1 3]]

print(a1%a2) # 相除取余數(shù)

#結(jié)果

[[4 0 2] [1 0 0]]

常用矩陣函數(shù)

同樣地,numpy中也定義了許多函數(shù),使用這些函數(shù)可以將函數(shù)作用于矩陣中的每個元素。 表格中默認(rèn)導(dǎo)入了


numpy模塊,即 import numpy as np 。a為ndarray對象。

 

常用矩陣函數(shù) 說明
np.sin(a) 對矩陣a中每個元素取正弦,sin(x)
np.cos(a) 對矩陣a中每個元素取余弦,cos(x)
np.tan(a) 對矩陣a中每個元素取正切,tan(x)
np.arcsin(a) 對矩陣a中每個元素取反正弦,arcsin(x)
np.arccos(a) 對矩陣a中每個元素取反余弦,arccos(x)
np.arctan(a) 對矩陣a中每個元素取反正切,arctan(x)
np.exp(a) 對矩陣a中每個元素取指數(shù)函數(shù),ex
np.sqrt(a) 對矩陣a中每個元素開根號


當(dāng)矩陣中的元素不在函數(shù)定義域范圍內(nèi),會產(chǎn)生RuntimeWarning,結(jié)果為nan(not a number)


矩陣乘法(點乘)


矩陣乘法必須滿足矩陣乘法的條件,即第一個矩陣的列數(shù)等于第二個矩陣的行數(shù)。 矩陣乘法的函數(shù)為 dot 。

import numpy as np

a1 = np.array([[1,2,3],[4,5,6]]) # a1為2*3矩陣

a2 = np.array([[1,2],[3,4],[5,6]]) # a2為3*2矩陣

print(a1.shape[1]==a2.shape[0]) # True, 滿足矩陣乘法條件 print(a1.dot(a2))

#a1.dot(a2)相當(dāng)于matlab中的a1*a2

#而Python中的a1*a2相當(dāng)于matlab中的a1.*a2

#結(jié)果

[[22 28]

[49 64]]

矩陣的轉(zhuǎn)置 a.T


import numpy as np

a = np.array([[1,2,3],[4,5,6]])

print(a.transpose())

#結(jié)果

[[1 4] [2 5] [3 6]]

矩陣的轉(zhuǎn)置還有更簡單的方法,就是a.T。


import numpy as np

a = np.array([[1,2,3],[4,5,6]])

print(a.T)

#結(jié)果

[[1 4] [2 5] [3 6]]

矩陣的逆


設(shè)A是數(shù)域上的一個n階方陣,若在相同數(shù)域上存在另一個n階矩陣B,使得: AB=BA=E。 則我們稱B是A的逆矩陣,而A則被稱為可逆矩陣。E是單位矩陣。


求矩陣的逆需要先導(dǎo)入 numpy.linalg ,用 linalg 的 inv 函數(shù)來求逆。矩陣求逆的條件是矩陣應(yīng)該是方陣。


import numpy as np

import numpy.linalg as lg

a = np.array([[1,2,3],[4,5,6],[7,8,9]])

print(lg.inv(a))

#結(jié)果

[[ ‐4.50359963e+15 9.00719925e+15 ‐4.50359963e+15]
[ 9.00719925e+15 ‐1.80143985e+16 9.00719925e+15]
[ ‐4.50359963e+15 9.00719925e+15 ‐4.50359963e+15]]

a = np.eye(3) # 3階單位矩陣

print(lg.inv(a)) # 單位矩陣的逆為他本身

#結(jié)果

[[ 1. 0. 0.]

[0. 1. 0.]

[0. 0. 1.]]

矩陣信息獲取(如均值等)


最值


獲得矩陣中元素最大最小值的函數(shù)分別是 max 和 min ,可以獲得整個矩陣、行或列的最大最小值。


import numpy as np

a = np.array([[1,2,3],[4,5,6]])

print(a.max()) #獲取整個矩陣的最大值 結(jié)果: 6

print(a.min()) #結(jié)果:1

#可以指定關(guān)鍵字參數(shù)axis來獲得行最大(小)值或列最大(?。┲?/p>

#axis=0 行方向最大(小)值,即獲得每列的最大(小)值

#axis=1 列方向最大(?。┲?,即獲得每行的最大(?。┲?/p>

#例如

print(a.max(axis=0)) # 每列的最大值

# 結(jié)果為 [4 5 6]

print(a.max(axis=1)) # 每行的最大值

#結(jié)果為 [3 6]

#要想獲得最大最小值元素所在的位置,可以通過argmax函數(shù)來獲得 print(a.argmax(axis=1))

#結(jié)果為 [2 2]

平均值


獲得矩陣中元素的平均值可以通過函數(shù) mean() 。同樣地,可以獲得整個矩陣、行或列的平均值。


import numpy as np

a = np.array([[1,2,3],[4,5,6]])

print(a.mean()) #結(jié)果為: 3.5

#同樣地,可以通過關(guān)鍵字axis參數(shù)指定沿哪個方向獲取平均值 print(a.mean(axis=0)) # 結(jié)果 [ 2.5 3.5 4.5] print(a.mean(axis=1)) # 結(jié)果 [ 2. 5.]

方差


方差的函數(shù)為 var() ,方差函數(shù) var() 相當(dāng)于函數(shù) mean(abs(x - x.mean())**2) ,其中x為矩陣。

import numpy as np

a = np.array([[1,2,3],[4,5,6]])

print(a.var()) # 結(jié)果 2.91666666667

print(a.var(axis=0)) # 結(jié)果 [ 2.25 2.25 2.25]

print(a.var(axis=1)) # 結(jié)果 [ 0.66666667 0.66666667]

標(biāo)準(zhǔn)差


標(biāo)準(zhǔn)差的函數(shù)為 std() 。 std() 相當(dāng)于 sqrt(mean(abs(x - x.mean())**2)) ,或相當(dāng)于 sqrt(x.var()) 。


import numpy as np

a = np.array([[1,2,3],[4,5,6]])

print(a.std()) # 結(jié)果 1.70782512766

print(a.std(axis=0)) # 結(jié)果 [ 1.5 1.5 1.5]

print(a.std(axis=1)) # 結(jié)果 [ 0.81649658 0.81649658]

中值

中值指的是將序列按大小順序排列后,排在中間的那個值,如果有偶數(shù)個數(shù),則是排在中間兩個數(shù)的平均值。中值

的函數(shù)是median(),調(diào)用方法為numpy.median(x,[axis]),axis可指定軸方向,默認(rèn)axis=None,對所有數(shù)取中值。


import numpy as np

x = np.array([[1,2,3],[4,5,6]])

print(np.median(x)) # 對所有數(shù)取中值

#結(jié)果

3.5

print(np.median(x,axis=0)) # 沿第一維方向取中值

#結(jié)果

[2.5 3.5 4.5]

print(np.median(x,axis=1)) # 沿第二維方向取中值

#結(jié)果

[2. 5.]

求和


矩陣求和的函數(shù)是sum(),可以對行,列,或整個矩陣求和

import numpy as np

a = np.array([[1,2,3],[4,5,6]])

print(a.sum()) # 對整個矩陣求和

#結(jié)果 21

print(a.sum(axis=0)) # 對列方向求和

# 結(jié)果 [5 7 9]

print(a.sum(axis=1)) # 對行方向求和

# 結(jié)果 [ 6 15]

累積和

某位置累積和指的是該位置之前(包括該位置)所有元素的和。例如序列[1,2,3,4,5],其累計和為[1,3,6,10,15],即第一個元素為1,第二個元素為1+2=3,……,第五個元素為1+2+3+4+5=15。矩陣求累積和的函數(shù)是cumsum(),可以對行,列,或整個矩陣求累積和。


import numpy as np

a = np.array([[1,2,3],[4,5,6]])

print(a.cumsum()) # 對整個矩陣求累積和

# 結(jié)果 [ 1 3 6 10 15 21]

print(a.cumsum(axis=0)) # 對列方向求累積和

#結(jié)果

[[1 2 3] [5 7 9]]

print( a.cumsum(axis=1)) # 對行方向求累積和

#結(jié)果

[[ 1 3 6]

[4 9 15]]

極差


>>>import numpy as np

>>>a = np.arange(10)

>>>a.ptp()

#結(jié)果是

9

百分位數(shù)

 

numpy.percentile(a, q, axis)

序號 參數(shù)及描述

1. a 輸入數(shù)組

2. q 要計算的百分位數(shù),在 0 ~ 100 之間

3. axis 沿著它計算百分位數(shù)的軸

 

加權(quán)平均值


>>>data = range(1,5)

>>>data

[1, 2, 3, 4]

>>>np.average(data)

2.5

>>>np.average(range(1,11), weights=range(10,0,‐1))

4.0

>>>data = np.arange(6).reshape((3,2))

>>>data

array([[0, 1],

[2, 3],

[4, 5]])

>>>np.average(data, axis=1, weights=[1./4, 3./4]) array([ 0.75, 2.75, 4.75])

>>>np.average(data, weights=[1./4, 3./4]) Traceback (most recent call last):
...

TypeError: Axis must be specified when shapes of a and weights differ.

Shape Manipulation


Changing the shape of an array

 

>>>a = np.floor(10*np.random.random((3,4)))

>>>a

array([[ 2., 8., 0., 6.],
[ 4., 5., 1., 1.],

[8., 9., 3., 6.]])

>>>a.shape

(3, 4)

數(shù)組的形狀可以用以下方式改變。Note that the following three commands all return a modified array, but do not change the original array:


>>>a.ravel() # returns the array, flattened

array([ 2., 8., 0., 6., 4., 5., 1., 1., 8., 9., 3., 6.])

>>>a.reshape(6,2) # returns the array with a modified shape array([[ 2., 8.],

[0., 6.],

[4., 5.],

[1., 1.],

[8., 9.],

[3., 6.]])

>>>a.T # returns the array, transposed

array([[ 2., 4., 8.],

[8., 5., 9.],

[0., 1., 3.],

[6., 1., 6.]])

>>>a.T.shape

(4, 3)

>>>a.shape (3, 4)


The reshape function returns its argument with a modified shape, whereas the ndarray.resize method modifies the array itself:


>>> a
array([[ 2., 8., 0., 6.],
[ 4., 5., 1., 1.],

[8., 9., 3., 6.]])

>>>a.resize((2,6))

>>>a

array([[ 2., 8., 0., 6., 4., 5.],
[ 1., 1., 8., 9., 3., 6.]])

If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated:


>>>a.reshape(3,‐1)

array([[ 2., 8., 0., 6.],

[ 4., 5., 1., 1.],

[8., 9., 3., 6.]])

Splitting one array into several smaller ones


Using hsplit , you can split an array along its horizontal axis, either by specifying the number of equally shaped arrays to return, or by specifying the columns after which the division should occur:


>>>a = np.floor(10*np.random.random((2,12)))

>>>a

array([[ 9., 5., 6., 3., 6., 8., 0., 7., 9., 7., 2., 7.],
[ 1., 4., 9., 2., 2., 1., 0., 6., 2., 2., 4., 0.]])
>>> np.hsplit(a,3) # Split a into 3
[array([[ 9., 5., 6., 3.],
[ 1., 4., 9., 2.]]), array([[ 6., 8., 0., 7.],
[ 2., 1., 0., 6.]]), array([[ 9., 7., 2., 7.],
[ 2., 2., 4., 0.]])]

 

Copies and Views


When operating and manipulating arrays, their data is sometimes copied into a new array and sometimes not. This is often a source of confusion for beginners. There are three cases:

No Copy At All(完全不復(fù)制)

a= b,改變b就相當(dāng)于改變a,或者相反。


>>>a = np.arange(12)

>>> b = a # no new object is created

>>> b is a # a and b are two names for the same ndarray object

True

>>>b.shape = 3,4# changes the shape of a

>>>a.shape

(3, 4)

View or Shallow Copy(視圖或淺復(fù)制)


Di?erent array objects can share the same data. The view method creates a new array object that looks at the same data.


>>>c = a.view()

>>>c is a False

>>> c.base is a # c is a view of the data owned by a
True
>>> c.flags.owndata # c并不擁有數(shù)據(jù)
False
>>>
>>> c.shape = 2,6 # a's shape doesn't change
>>> a.shape
(3, 4)
>>> c[0,4] = 1234 # a's data changes a 的數(shù)據(jù)也會變
>>> a
array([[ 0, 1, 2, 3],
[1234, 5, 6, 7],
[ 8, 9, 10, 11]])

Slicing an array returns a view of it:


>>>s = a[:,1:3] # spaces added for clarity; could also be written "s = a[:,1:3]"

>>>s[:] = 10# s[:] is a view of s. Note the difference between s=10 and s[:]=10

>>>a

array([[ 0, 10, 10, 3],

[1234, 10, 10, 7],

[8, 10, 10, 11]])

Deep Copy(深復(fù)制)

 

The copy method makes a complete copy of the array and its data.

>>> d = a.copy() # a new array object with new data is created

>>>d is a False

# d沒有和a共享任何數(shù)據(jù)

>>> d.base is a # d doesn't share anything with a

False

>>>d[0,0] = 9999

>>>a

array([[ 0, 10, 10, 3],

[1234, 10, 10, 7],

[8, 10, 10, 11]])


numpy 關(guān)于 copy 有三種情況,完全不復(fù)制、視圖(view)或者叫淺復(fù)制( shadow copy )和深復(fù)制( deep

copy )。而 b = a[:] 就屬于第二種,即視圖,這本質(zhì)上是一種切片操作( slicing ),所有的切片操作返回的


都是視圖。具體來說, b = a[:] 會創(chuàng)建一個新的對象 b (所以說 id 和 a 不一樣),但是 b 的數(shù)據(jù)完全來自于 a ,和 a 保持完全一致,換句話說,b的數(shù)據(jù)完全由a保管,他們兩個的數(shù)據(jù)變化是一致的,可以看下面的示例:


a = np.arange(4) # array([0, 1, 2, 3])

b = a[:] # array([0, 1, 2, 3])

b.flags.owndata # 返回 False,b 并不保管數(shù)據(jù)

a.flags.owndata # 返回 True,數(shù)據(jù)由 a 保管

#改變 a 同時也影響到 b

a[‐1] = 10 # array([0, 1, 2, 10])

b# array([0, 1, 2, 10])

#改變 b 同時也影響到 a

b[0] = 10 # array([10, 1, 2, 10])

a# array([10, 1, 2, 10])


b = a 和 b = a[:] 的差別就在于后者會創(chuàng)建新的對象,前者不會。兩種方式都會導(dǎo)致 a 和 b 的數(shù)據(jù)相互影響。要想不讓 a 的改動影響到 b ,可以使用深復(fù)制: unique_b = a.copy()


曼德勃羅

 

import numpy as np

import matplotlib.pyplot as plt

def mandelbrot( h,w, maxit=20 ):

"""Returns an image of the Mandelbrot fractal of size (h,w)."""

y,x = np.ogrid[ ‐1.4:1.4:h*1j, ‐2:0.8:w*1j ]

c = x+y*1j

z = c

divtime = maxit + np.zeros(z.shape, dtype=int)


for i in range(maxit):

z = z**2 + c

diverge = z*np.conj(z) > 2**2

div_now = diverge & (divtime==maxit)

divtime[div_now] = i

 

 


# who is diverging

# who is diverging now

# note when

z[diverge] = 2 # avoid diverging too much

return divtime

plt.imshow(mandelbrot(400,400))

plt.show()

 

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多