import numpy as np
a = np.array([1, 2, 3, 4]) # 建立array
print("a:", a)
print("type:", type(a)) # 型別為ndarray
print("ndim:", a.ndim) # 維度
# arange
a = np.arange(10)
print(type(a))
print(a)
print(np.arange(3, 6, 0.4))
# linspace
print(np.linspace(4, 6, 5))
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")
c = np.zeros((2, 3, 4)) # 建立全為0的陣列
print(c)
d = np.ones((2, 3)) # 建立全為1的陣列
print(d)
print("ndim:", d.ndim)
print("shape:", d.shape)
print("dtype:", d.dtype)
# 改變儲存的type
d = d.astype('int32')
print(d)
print(d.dtype)
print(type(d[0, 0]))
# 改變形狀
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)
h = np.array([[1, 2, 3], [4, 5, 6]])
l = h.reshape((3, -1)) # 會自動計算-1那個位子應該是多少
print(l)
m = h.reshape((2, 2)) # 大小不符合
# 一維陣列
o = np.array([0, 1, 2, 3, 4, 5])
print(o[1])
print(o[1:5]) # slice
print(o[::-1])
# 二維陣列
p = np.array(range(12))
p = p.reshape((3, -1))
print(p)
print(p[0])
print(p[2, 0])
# 更多切片
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")
u = np.array([1, 2, 3, 4, 5, 6])
v = u
v[0] = 87
print("u:", u)
print("v:", v)
w = np.array([[1, 2, 3], [4, 5, 6]])
x = w.copy()
x[0, 0] = 87
print("w:", w)
print("x:", x)
z = np.arange(12).reshape((3, -1))
for i in z:
for j in i:
print(j, end = ' ')
for i in range(z.shape[0]):
for j in range(z.shape[1]):
print(z[i, j], end = ' ')
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)) # 內積
# 矩陣乘法
C = np.array([[1, 2], [3, 4]])
D = np.array([[2, 8], [5, 1]])
print(np.matmul(C, D))
F = np.array([[1, 2], [3, 4]])
print(F.sum())
print(F.max())
print(F.min())
print(F.mean())
E = np.array([[-1, 2, 3, -2], [3, -9, 5, -3]])
E[E<0]=0
print(E)