numpy 幾種屬性
- ndim: 維度
- shape: 行數(shù)和列數(shù)
- size: 元素個(gè)數(shù)
打印 numpy 的幾種屬性
print('number of dim:',array.ndim) # 維度
# number of dim: 2
print('shape :',array.shape) # 行數(shù)和列數(shù)
# shape : (2, 3)
print('size:',array.size) # 元素個(gè)數(shù)
# size: 6
numpy 創(chuàng)建 array
- array:創(chuàng)建數(shù)組
- dtype:指定數(shù)據(jù)類(lèi)型
- zeros:創(chuàng)建數(shù)據(jù)全為0
- ones:創(chuàng)建數(shù)據(jù)全為1
- empty:創(chuàng)建數(shù)據(jù)接近0
- arrange:按指定范圍創(chuàng)建數(shù)據(jù)
- linspace:創(chuàng)建線段
創(chuàng)建數(shù)組
a = np.array([2, 23, 4]) # 一維數(shù)組
print(a)
# [2 23 4]
創(chuàng)建全 1 數(shù)組
a = np.ones((3, 4), dtype = np.int) # 創(chuàng)建 3 行 4 列的全 1 數(shù)組孝扛,數(shù)據(jù)類(lèi)型為 int 型
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
使用 reshape 改變數(shù)據(jù)形狀
a = np.arange(12).reshape((3, 4))
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
numpy 的幾種基本運(yùn)算
c = a+b
c = a*b # 對(duì)應(yīng)元素相乘
c = b**2 # b 的二次方
c = 10*np.sin(a) # 調(diào)用 numpy 中的 sin 函數(shù)
print(b<3) # 進(jìn)行邏輯判斷,返回 bool 類(lèi)型數(shù)據(jù)
c_dot = np.dot(a, b) # 矩陣乘法
索引
import numpy as np
A = np.arange(3,15)
# array([3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
print(A[3])
# 6
A = np.arange(3,15).reshape((3,4))
array([[ 3, 4, 5, 6]
[ 7, 8, 9, 10]
[11, 12, 13, 14]])
print(A[2])
# [11 12 13 14]
print(A[1, 1:3]) # [8 9] # 切片處理
for row in A:
print(row) # 使用 for 函數(shù)進(jìn)行打印
[ 3, 4, 5, 6]
[ 7, 8, 9, 10]
[11, 12, 13, 14]
array 上下合并 np.vstack()
import numpy as np
A = np.array([1,1,1])
B = np.array([2,2,2])
print(np.vstack((A,B))) # vertical stack
[[1,1,1]
[2,2,2]]
C = np.vstack((A,B))
print(A.shape,C.shape) # 合并后的 array 屬性
# (3,) (2,3)
array 左右合并 np.hstack()
D = np.hstack((A,B)) # horizontal stack
print(D)
# [1,1,1,2,2,2]
print(A.shape,D.shape)
# (3,) (6,)
array 多個(gè)矩陣或序列合并時(shí) concatenate函數(shù)
C = np.concatenate((A,B,B,A),axis=0)
print(C)
"""
array([[1],
[1],
[1],
[2],
[2],
[2],
[2],
[2],
[2],
[1],
[1],
[1]])
"""
D = np.concatenate((A,B,B,A),axis=1)
print(D)
"""
array([[1, 2, 2, 1],
[1, 2, 2, 1],
[1, 2, 2, 1]])
"""
print(help()) # 打印幫助文檔
print(X.shape) # 查看 X 的數(shù)據(jù)格式(多少行多少列)
axis參數(shù)很好的控制了矩陣的縱向或是橫向打印苦始,相比較vstack和hstack函數(shù)顯得更加方便陌选。
numpy讀取文本讀出來(lái)的是數(shù)組的形式