numpy的簡單使用

一、Numpy是什麼?

  • 1.Numrical Python,數值的Python,應用於數值分析領域的Python語言工具;
  • 2.Numpy是一個開源的科學計算庫;
  • 3.Numpy彌補了作爲通用編程語言的Python在數值計算方面,能力弱,速度慢的不足;
  • 4.Numpy擁有豐富的數學函數、強大的多維數組和優異的運算性能;
  • 5.Numpy與Scipy、scikit、matplotlib等其它科學計算庫可以很好地協調工作;
  • 6.Numpy可以取代matlab等工具,允許用戶進行快速開發的同時完成交互式的原型設計。

python 和 numpy 在運算上的耗時對比:

import datetime as dt
import numpy as np
n = 100000
start = dt.datetime.now()
A, B = [], []
for i in range(n):
    A.append(i ** 2)
    B.append(i ** 3)
C = []
for a, b in zip(A, B):
    C.append(a + b)
print("python耗時:", (dt.datetime.now() - start).microseconds)
start = dt.datetime.now()
C = np.arange(n) ** 2 + np.arange(n) ** 3
print("numpy耗時:", (dt.datetime.now() - start).microseconds)
python耗時: 101686
numpy耗時: 3372

二、多維數組

1.numpy.ndarray

numpy中的多維數組是numpy.ndarray類類型的對象,可用於表示數據結構中的任意維度的數組;

2.創建多維數組對象

numpy.arange(起始, 終止, 步長)->一維數組,首元素就是起始值,尾元素爲終止值之前的最後一個元素,步長即每次遞增的公差。缺省起始值爲0,缺省步長爲1。
numpy.array(任何可被解釋爲數組的容器)

3.內存連續,元素同質。

4.ndarray.dtype屬性

表示元素的數據類型。通過dtype參數和astype()方法可以指定和修改元素的數據類型。

5.ndarray.shape屬性

    表示數組的維度:(高維度數, ..., 低維度數)
import numpy as np
a = np.arange(10)
print(a)
b = np.arange(1, 10)
print(b)
c = np.arange(1, 10, 2)
print(c)
d = np.array([])
print(d)
e = np.array([10, 20, 30, 40, 50])
print(e)
f = np.array([
    [1, 2, 3],
    [4, 5, 6]])
print(f)
print(type(f))
print(type(f[0][0]))
print(f.dtype)
g = np.array(['1', '2', '3'], dtype=np.int32)
print(type(g[0]))
print(g.dtype)
h = g.astype(np.str_)
print(type(h[0]))
print(h.dtype)
print(e.shape)
print(f.shape)
i = np.array([
    [np.arange(1, 5), np.arange(5, 9), np.arange(9, 13)],
    [np.arange(13, 17), np.arange(17, 21), np.arange(21, 25)]])
print(i.shape)
print(i)
[0 1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 3 5 7 9]
[]
[10 20 30 40 50]
[[1 2 3]
 [4 5 6]]
<class 'numpy.ndarray'>
<class 'numpy.int64'>
int64
<class 'numpy.int32'>
int32
<class 'numpy.str_'>
<U11
(5,)
(2, 3)
(2, 3, 4)
[[[ 1  2  3  4]
  [ 5  6  7  8]
  [ 9 10 11 12]]

 [[13 14 15 16]
  [17 18 19 20]
  [21 22 23 24]]]

6.元素索引,從0開始

    數組[索引]
    數組[行索引][列索引]
    數組[頁索引][行索引][列索引]
    數組[頁索引, 行索引, 列索引]
import numpy as np
a = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(a)
print(a[0])
print(a[0][0])
print(a[0][0][0])
for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        for k in range(a.shape[2]):
            print(a[i][j][k], a[i, j, k])
b = np.array([1, 2, 3], dtype=int)  # int->np.int32
print(b.dtype)
c = b.astype(float)  # float->np.float64
print(c.dtype)
d = c.astype(str)  # str->np.str_
print(d.dtype)
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]
[[1 2]
 [3 4]]
[1 2]
1
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
int64
float64
<U32

7.numpy的內置類型和自定義類型

1)numpy的內置類型
    bool_ 1字節布爾型,True(1)/False(0)
    int8 1字節有符號整型,-128 - 127
    int16 2字節有符號整型
    int32 4字節有符號整型
    int64 8字節有符號整型
    uint8 1字節無符號整型,0 - 255
    uint16 2字節無符號整型
    uint32 4字節無符號整型
    uint64 8字節無符號整型
    float16 2字節浮點型
    float32 4字節浮點型
    float64 8字節浮點型
    complex64 8字節複數型
    complex128 16字節複數型
    str_ 字符串型
2)自定義類型
    通過dtype將多個相同或者不同的numpy內置類型組合成某種複合類型,用於數組元素的數據類型。除了使用內置類型的全稱以外還可以通過類型編碼字符串簡化類型的說明。
    numpy.int8 -> i1
    numpy.int16 -> i2
    numpy.uint32 -> u4
    numpy.float64 -> f8
    numpy.complex128 -> c16

對於多字節整數可以加上字節序前綴:

= - 處理器系統默認; < - 小端字節序,低數位低地址; > - 大端字節序,低數位高地址。
98

0x1234

L H
0x34 0x12 L H
0x12 0x34
numpy.str_ -> U字符數
numpy.bool_ -> b

import numpy as np
a = np.array([('ABC', [1, 2, 3])], dtype='U3, 3i4')
print(a)
print(a[0]['f0'])
print(a[0]['f1'][0])
print(a[0]['f1'][1])
print(a[0]['f1'][2])
b = np.array([('ABC', [1, 2, 3])], dtype=[
    ('name', np.str_, 3), ('scores', np.int32, 3)])
print(b)
print(b[0]['name'])
print(b[0]['scores'][0])
print(b[0]['scores'][1])
print(b[0]['scores'][2])
c = np.array([('ABC', [1, 2, 3])], dtype={
    'names': ['name', 'scores'],
    'formats': ['U3', '3i4']})
print(c)
print(c[0]['name'])
print(c[0]['scores'][0])
print(c[0]['scores'][1])
print(c[0]['scores'][2])
d = np.array([('ABC', [1, 2, 3])], dtype={
    'name': ('U3', 0), 'scores': ('3i4', 12)})
print(d)
print(d[0]['name'])
print(d[0]['scores'][0])
print(d[0]['scores'][1])
print(d[0]['scores'][2])
e = np.array([0x1234], dtype=(
    '>u2', {'lo': ('u1', 0), 'hi': ('u1', 1)}))
print('{:x}'.format(e[0]))
print('{:x} {:x}'.format(e['lo'][0], e['hi'][0]))
[('ABC', [1, 2, 3])]
ABC
1
2
3
[('ABC', [1, 2, 3])]
ABC
1
2
3
[('ABC', [1, 2, 3])]
ABC
1
2
3
[('ABC', [1, 2, 3])]
ABC
1
2
3
1234
12 34

8.切片

數組[起始:終止:步長, 起始:終止:步長, …]
缺省起始:首(步長爲正)、尾(步長爲負)
缺省終止:尾後(步長爲正)、首前(步長爲負)
缺省步長:1
靠近端部的一個或幾個連續的維度使用缺省切片,可以用"…"表示。

import numpy as np
a = np.arange(1, 10)
print(a)
print(a[:3])  # 1 2 3
print(a[3:6])  # 4 5 6
print(a[6:])  # 7 8 9
print(a[::-1])  # 9 8 7 6 5 4 3 2 1
print(a[:-4:-1])  # 9 8 7
print(a[-4:-7:-1])  # 6 5 4
print(a[-7::-1])  # 3 2 1
print(a[::])  # 1 2 3 4 5 6 7 8 9
print(a[...])  # 1 2 3 4 5 6 7 8 9
print(a[:])  # 1 2 3 4 5 6 7 8 9
# print(a[])  # error
print(a[::3])  # 1 4 7
print(a[1::3])  # 2 5 8
print(a[2::3])  # 3 6 9
b = np.arange(1, 25).reshape(2, 3, 4)
print(b)
print(b[:, 0, 0])  # 1 13
print(b[0, :, :])
print(b[0, ...])
print(b[0, 1, ::2])  # 5 7
print(b[..., 1])
print(b[:, 1])
print(b[-1, 1:, 2:])
[1 2 3 4 5 6 7 8 9]
[1 2 3]
[4 5 6]
[7 8 9]
[9 8 7 6 5 4 3 2 1]
[9 8 7]
[6 5 4]
[3 2 1]
[1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 4 7]
[2 5 8]
[3 6 9]
[[[ 1  2  3  4]
  [ 5  6  7  8]
  [ 9 10 11 12]]

 [[13 14 15 16]
  [17 18 19 20]
  [21 22 23 24]]]
[ 1 13]
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
[5 7]
[[ 2  6 10]
 [14 18 22]]
[[ 5  6  7  8]
 [17 18 19 20]]
[[19 20]
 [23 24]]

9.改變維度

1)視圖變維:針對一個數組對象獲取其不同維度的視圖
    數組.reshape(新維度)->數組的新維度視圖
    數組.ravel()->數組的一維視圖
2)複製變維:針對一個數組對象獲取其不同維度的副本
    數組.flatten()->數組的一維副本
3)就地變維
    數組.shape = (新維度)
    數組.resize(新維度)
4)視圖轉置
    數組.transpose()->數組的轉置視圖
    數組.T: 轉置視圖屬性
    至少二維數組才能轉置。
import numpy as np
a = np.arange(1, 9)
print(a)
b = a.reshape(2, 4)
print(b)
c = b.reshape(2, 2, 2)
print(c)
d = c.ravel()
print(d)
e = c.flatten()
print(e)
f = b.reshape(2, 2, 2).copy()
print(f)
a += 10
print(a, b, c, d, e, f, sep='\n')
a.shape = (2, 2, 2)
print(a)
a.resize(2, 4)
print(a)
#g = a.transpose()
#g = a.reshape(4, 2)
g = a.T
print(g)
# print(np.array([e]).T)
print(e.reshape(-1, 1))
[1 2 3 4 5 6 7 8]
[[1 2 3 4]
 [5 6 7 8]]
[[[1 2]
  [3 4]]

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

 [[5 6]
  [7 8]]]
[11 12 13 14 15 16 17 18]
[[11 12 13 14]
 [15 16 17 18]]
[[[11 12]
  [13 14]]

 [[15 16]
  [17 18]]]
[11 12 13 14 15 16 17 18]
[1 2 3 4 5 6 7 8]
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]
[[[11 12]
  [13 14]]

 [[15 16]
  [17 18]]]
[[11 12 13 14]
 [15 16 17 18]]
[[11 15]
 [12 16]
 [13 17]
 [14 18]]
[[1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]
 [8]]

10.組合與拆分

1)垂直組合/拆分
    numpy.vstack((上, 下))
    numpy.vsplit(數組, 份數)->子數組集合
2)水平組合/拆分
    numpy.hstack((左, 右))
    numpy.hsplit(數組, 份數)->子數組集合
3)深度組合/拆分
    numpy.dstack((前, 後))
    numpy.dsplit(數組, 份數)->子數組集合
4)行/列組合
    numpy.row_stack((上, 下))
    numpy.column_stack((左, 右))
import numpy as np
a = np.arange(11, 20).reshape(3, 3)
b = np.arange(21, 30).reshape(3, 3)
print(a, b, sep='\n')
c = np.vstack((a, b))
print(c)
a, b = np.vsplit(c, 2)
print(a, b, sep='\n')
c = np.hstack((a, b))
print(c)
a, b = np.hsplit(c, 2)
print(a, b, sep='\n')
c = np.dstack((a, b))
print(c)
a, b = np.dsplit(c, 2)
print(a.T[0].T, b.T[0].T, sep='\n')
a = a.ravel()
b = b.ravel()
print(a, b, sep='\n')
c = np.row_stack((a, b))
#c = np.vstack((a, b))
print(c)
#c = np.column_stack((a, b))
#c = np.hstack((a, b))
c = np.c_[a, b]
print(c)
[[11 12 13]
 [14 15 16]
 [17 18 19]]
[[21 22 23]
 [24 25 26]
 [27 28 29]]
[[11 12 13]
 [14 15 16]
 [17 18 19]
 [21 22 23]
 [24 25 26]
 [27 28 29]]
[[11 12 13]
 [14 15 16]
 [17 18 19]]
[[21 22 23]
 [24 25 26]
 [27 28 29]]
[[11 12 13 21 22 23]
 [14 15 16 24 25 26]
 [17 18 19 27 28 29]]
[[11 12 13]
 [14 15 16]
 [17 18 19]]
[[21 22 23]
 [24 25 26]
 [27 28 29]]
[[[11 21]
  [12 22]
  [13 23]]

 [[14 24]
  [15 25]
  [16 26]]

 [[17 27]
  [18 28]
  [19 29]]]
[[11 12 13]
 [14 15 16]
 [17 18 19]]
[[21 22 23]
 [24 25 26]
 [27 28 29]]
[11 12 13 14 15 16 17 18 19]
[21 22 23 24 25 26 27 28 29]
[[11 12 13 14 15 16 17 18 19]
 [21 22 23 24 25 26 27 28 29]]
[[11 21]
 [12 22]
 [13 23]
 [14 24]
 [15 25]
 [16 26]
 [17 27]
 [18 28]
 [19 29]]

11.ndarray類的屬性

    dtype - 元素類型
    shape - 數組維度
    T - 轉置視圖
    ndim - 維數
    size - 元素數, 僅對一維數組等價於len()
    itemsize - 元素字節數
    nbytes - 總字節數 = size x itemsize
    flat - 扁平迭代器
    real - 實部數組
    imag - 虛部數組
    數組.tolist()->列表對象
import numpy as np
a = np.array([
    [1 + 1j, 2 + 4j, 3 + 7j],
    [4 + 2j, 5 + 5j, 6 + 8j],
    [7 + 3j, 8 + 6j, 9 + 9j]])
print(a.dtype, a.dtype.str, a.dtype.char)
print(a.shape)
print(a.ndim)
print(a.size, len(a))
print(a.itemsize)
print(a.nbytes)
print(a.T)
print(a.real, a.imag, sep='\n')
for elem in a.flat:
    print(elem)
print(a.flat[[1, 3, 5]])
a.flat[[2, 4, 6]] = 0
print(a)


def fun(a, b):
    a.append(b)
    return a


x = np.array([10, 20, 30])
y = 40
x = np.array(fun(x.tolist(), y))
print(x)
x = np.append(x, 50)
print(x)
complex128 <c16 D
(3, 3)
2
9 3
16
144
[[ 1.+1.j  4.+2.j  7.+3.j]
 [ 2.+4.j  5.+5.j  8.+6.j]
 [ 3.+7.j  6.+8.j  9.+9.j]]
[[ 1.  2.  3.]
 [ 4.  5.  6.]
 [ 7.  8.  9.]]
[[ 1.  4.  7.]
 [ 2.  5.  8.]
 [ 3.  6.  9.]]
(1+1j)
(2+4j)
(3+7j)
(4+2j)
(5+5j)
(6+8j)
(7+3j)
(8+6j)
(9+9j)
[ 2.+4.j  4.+2.j  6.+8.j]
[[ 1.+1.j  2.+4.j  0.+0.j]
 [ 4.+2.j  0.+0.j  6.+8.j]
 [ 0.+0.j  8.+6.j  9.+9.j]]
[10 20 30 40]
[10 20 30 40 50]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章