NumPy入門

Numpy是Python科學(xué)計(jì)算中最常用的工具,包括SciPy以及Pandas等工具也有對(duì)NumPy的依賴,因此Python科學(xué)計(jì)算應(yīng)當(dāng)從NumPy開(kāi)始。

ndarray

ndarray是NumPy的核心數(shù)據(jù)類型,包括Pandas的DataFrame類型也與它有互轉(zhuǎn)的方法。按其名稱ndarray來(lái)看用的比較多的是矩陣運(yùn)算。

創(chuàng)建

# coding:utf8
import numpy as np

a = np.array([1, 2, 3, 4])  # 使用list初始化
b = np.array((5, 6, 7, 8))  # 使用tuple初始化
c = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])  # 使用嵌套list初始化
print type(a)   # <type 'numpy.ndarray'>
print b.shape   # (4,)
print c.shape   # (2, 4)

print c
# [[1 2 3 4]
#  [5 6 7 8]]
c.shape = (4, 2)    # 更改shape屬性 也可指定為(4, -1) or (-1, 2)
print c
print c.dtype   # int64
# ndarray在內(nèi)存中連續(xù)存儲(chǔ),更改shape之后矩陣也隨之更改
# [[1 2]
#  [3 4]
#  [5 6]
#  [7 8]]

d = a.reshape(2, 2)
# 此時(shí)a與d共享內(nèi)存空間
print d

t = a.astype(np.float64)    # 轉(zhuǎn)換類型
print t

# float64 的別名
print [key for key, value in np.typeDict.items() if value is np.float64]

自動(dòng)生成數(shù)組

# coding:utf8
import numpy as np
# 數(shù)組的自動(dòng)生成

# 0到1(不包括)以0.1為步長(zhǎng)生成數(shù)組
a = np.arange(0, 1, 0.1)
print a
# [ 0.   0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9]
print type(a)
# <type 'numpy.ndarray'>

# 0到1(使用endpoint確定是否包括,默認(rèn)True)取10個(gè)數(shù)
b = np.linspace(0, 1, 10, endpoint=False)
print b
# [ 0.   0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9]
c = np.linspace(0, 1, 10)
print c
# [ 0.          0.11111111  0.22222222  0.33333333  0.44444444  0.55555556
#  0.66666667  0.77777778  0.88888889  1.        ]

# 10**0 到 10**2 取等比3個(gè)
d = np.logspace(0, 2, 3, endpoint=True, base=10.0)
print d
# [   1.   10.  100.]
print d.dtype   # float64

e = np.zeros((2, 3), dtype='float')
print e
# [[ 0.  0.  0.]
#  [ 0.  0.  0.]]

f = np.ones((2, 3), dtype='int')
print f
# [[1 1 1]
#  [1 1 1]]

# 未初始化內(nèi)存
g = np.empty((2, 4))
print g
# [[  6.90359047e-310   6.90359047e-310   1.58101007e-322   3.16202013e-322]
#  [  0.00000000e+000   1.17133162e-316   1.17133162e-316   1.17133162e-316]]

# 填充
h = np.full((2, 3), 6.0)
print h
# [[ 6.  6.  6.]
#  [ 6.  6.  6.]]

s = 'abcd'
i = np.fromstring(s, dtype=np.int8)
print i
# [ 97  98  99 100]

# 通過(guò)函數(shù)創(chuàng)建數(shù)組 這里輸出乘法表
j = np.fromfunction(lambda x, y: (x + 1) * (y + 1), (9, 9), dtype=int)
print j

存取元素

# coding:utf8
import numpy as np

# 存取元素
a = np.arange(0, 10, 1)
print a
# [0 1 2 3 4 5 6 7 8 9]

# 切片
print a[3:5]
# [3, 4]    與list切片一致
print a[:5]
# [0 1 2 3 4] 省略0
print a[::-1]
# [9 8 7 6 5 4 3 2 1 0] 逆
print a[5:1:-2]
# [5 3]
a[2:4] = 100, 101
# 更改
print a
# [  0   1 100 101   4   5   6   7   8   9]

# 高級(jí)用法
b = a[[1, 3, 6, 8]]  # 取a的第1,2,6,8組成新的,不共享內(nèi)存
c = a[np.array([[1, 3, 6, 8], [2, 5, 7, -3]])]
d = a[[1, 3, 6, 8, 2, 5, 7, -3]].reshape(2, 4)
print c == d    # 2*4 的 True
# 判斷
print a[a < 7]  # [0 1 4 5 6]

e = np.arange(5, 0, -1)
# 長(zhǎng)度一致,取True對(duì)應(yīng)元素
print e[np.array([True, False, True, False, False])]
# [5, 3]

# randint(low, high, size, dtype)
f = np.random.randint(0, 10, 4)
print f

ufunc

# coding:utf8
import numpy as np

# ufunc
# 所謂的ufunc即對(duì)array每個(gè)數(shù)值進(jìn)行操作的函數(shù)

a = np.linspace(0, 2*np.pi, 10)
print a
# 對(duì)a的每個(gè)值進(jìn)行sin操作,輸出也可指定為a
b = np.sin(a, out=a)
print a == b    # 1*10 True

c = np.arange(6.0).reshape((2, 3))
print c
print c.item(1, 2)  # 取c的1行2列(始于0行0列)

# 四則
d = np.arange(10)
e = np.arange(10, 0, -1)
f = np.arange(5)
print d + e
# print e + f     # err
print np.add(d, e)
# np.add(x1, x2, out=x1)
# np.subtract() np.multiply()
# np.divide() np.true_divide() np.floor_divide()
# np.negative() np.power() np.mod() np.remainder()
# np.equal() np.not_equal() np.less() np.greater()
# np.logical_and() or not xor

函數(shù)庫(kù)(常用部分)

# coding: utf8
import numpy as np
# 函數(shù)庫(kù)
# 隨機(jī)數(shù)
print np.random.rand(3, 4)
print np.random.randn(3, 4)

# 統(tǒng)計(jì)
a = np.random.randint(0, 10, (3, 4))
print a
print a.sum()
print a.sum(keepdims=True)  # 保持維數(shù)
print a.var()
print a.mean()
print a.std()
print a.prod()
print np.average(a)
# 大小與排序
print a.max()
print a.min()
print a.argmin()    # 最小值下標(biāo)
print a.sort()
print np.median(a)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容