NumPy

ndarray

In [48]:
import numpy as np

a = np.array([1, 2, 3, 4]) # 建立array

print("a:", a)
print("type:", type(a))    # 型別為ndarray
print("ndim:", a.ndim)     # 維度
a: [1 2 3 4]
type: <class 'numpy.ndarray'>
ndim: 1
In [135]:
# arange
a = np.arange(10)
print(type(a))
print(a)
print(np.arange(3, 6, 0.4))
<class 'numpy.ndarray'>
[0 1 2 3 4 5 6 7 8 9]
[3.  3.4 3.8 4.2 4.6 5.  5.4 5.8]
In [137]:
# linspace
print(np.linspace(4, 6, 5))
[4.  4.5 5.  5.5 6. ]
In [165]:
b = np.array([[1, 2, 3, 4], [4, 3, 2, 1], [1, 3, 5, 7]])
print(b)
print("ndim:", b.ndim)
print("shape:", b.shape)
print("dtype:", b.dtype)
print("size:", b.size)
print("transpose:", b.T, sep="\n")
[[1 2 3 4]
 [4 3 2 1]
 [1 3 5 7]]
ndim: 2
shape: (3, 4)
dtype: int64
size: 12
transpose:
[[1 4 1]
 [2 3 3]
 [3 2 5]
 [4 1 7]]
In [166]:
c = np.zeros((2, 3, 4)) # 建立全為0的陣列
print(c)
[[[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]

 [[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]]
In [167]:
d = np.ones((2, 3)) # 建立全為1的陣列
print(d)
print("ndim:", d.ndim)
print("shape:", d.shape)
print("dtype:", d.dtype)
[[1. 1. 1.]
 [1. 1. 1.]]
ndim: 2
shape: (2, 3)
dtype: float64
In [66]:
# 改變儲存的type
d = d.astype('int32')
print(d)
print(d.dtype)
print(type(d[0, 0]))
[[1 1 1]
 [1 1 1]]
int32
<class 'numpy.int32'>

reshape

In [168]:
# 改變形狀
e = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
f = e.reshape((2, 6))
g = e.reshape((2, 2, 3))
print(f)
print()
print(g)
[[ 1  2  3  4  5  6]
 [ 7  8  9 10 11 12]]

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

 [[ 7  8  9]
  [10 11 12]]]
In [169]:
h = np.array([[1, 2, 3], [4, 5, 6]])
l = h.reshape((3, -1)) # 會自動計算-1那個位子應該是多少
print(l)
[[1 2]
 [3 4]
 [5 6]]
In [170]:
m = h.reshape((2, 2)) # 大小不符合
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-170-c7722b6618e8> in <module>()
----> 1 m = h.reshape((2, 2)) # 大小不符合

ValueError: cannot reshape array of size 6 into shape (2,2)

陣列索引&切片

In [95]:
# 一維陣列
o = np.array([0, 1, 2, 3, 4, 5])
print(o[1])
print(o[1:5]) # slice
print(o[::-1])
1
[1 2 3 4]
[5 4 3 2 1 0]
In [171]:
# 二維陣列
p = np.array(range(12))
p = p.reshape((3, -1))
print(p)
print(p[0])
print(p[2, 0])
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[0 1 2 3]
8
In [172]:
# 更多切片
q = np.array(range(30)).reshape((5, -1))
r = q[1:4, ::2]
s = q[(0, 1, 4), (1, 3, 5)]
t = q[3:, (0, 4, 2)]
y = q[q%4==0]
print("q", q, sep = "\n")
print("r", r, sep = "\n")
print("s", s, sep = "\n")
print("t", t, sep = "\n")
print("y", y, sep = "\n")
q
[[ 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]]
r
[[ 6  8 10]
 [12 14 16]
 [18 20 22]]
s
[ 1  9 29]
t
[[18 22 20]
 [24 28 26]]
y
[ 0  4  8 12 16 20 24 28]

複製

In [127]:
u = np.array([1, 2, 3, 4, 5, 6])
v = u
v[0] = 87
print("u:", u)
print("v:", v)
u: [87  2  3  4  5  6]
v: [87  2  3  4  5  6]
In [131]:
w = np.array([[1, 2, 3], [4, 5, 6]])
x = w.copy()
x[0, 0] = 87
print("w:", w)
print("x:", x)
w: [[1 2 3]
 [4 5 6]]
x: [[87  2  3]
 [ 4  5  6]]

遍歷

In [173]:
z = np.arange(12).reshape((3, -1))
for i in z:
    for j in i:
        print(j, end = ' ')
0 1 2 3 4 5 6 7 8 9 10 11 
In [148]:
for i in range(z.shape[0]):
    for j in range(z.shape[1]):
        print(z[i, j], end = ' ')
0 1 2 3 4 5 6 7 8 9 10 11 

運算

In [157]:
A = np.arange(5)
B = np.array([1, 2, 3, 0, 1])
print(A)
print(A+3)  # 每個元素都+3
print(A*2)  # 每個元素都*2
print(A**2) # 每個元素都平方
print(A+B)  # A, B相加
print(A*B)  # A, B相同位置相乘
print(A.dot(B)) # 內積
[0 1 2 3 4]
[3 4 5 6 7]
[0 2 4 6 8]
[ 0  1  4  9 16]
[1 3 5 3 5]
[0 2 6 0 4]
12
In [159]:
# 矩陣乘法
C = np.array([[1, 2], [3, 4]])
D = np.array([[2, 8], [5, 1]])
print(np.matmul(C, D))
[[12 10]
 [26 28]]
In [163]:
F = np.array([[1, 2], [3, 4]])
print(F.sum())
print(F.max())
print(F.min())
print(F.mean())
10
4
1
2.5

取代

In [161]:
E = np.array([[-1, 2, 3, -2], [3, -9, 5, -3]])
E[E<0]=0
print(E)
[[0 2 3 0]
 [3 0 5 0]]