NumPy的简单用法

1. 指定数据类型

student_type = np.dtype([('name', 'U20'), ('sex', 'U1'), ('age', 'i1'), ('marks', 'f4')])
students = np.array([('张三', '', 18, 87.6), ('李四', '', 19, 100),  ('王五', '', 28, 85.5)], dtype=student_type)

2. 等步长,平均分, 等比 初始化NumPy矩阵

x = np.arange(10, 20, 3)
# 平均分
x1 = np.linspace(10,20, 2)
# 等比数列 以base为基数, base的3次方 等比拆分10份数
x2 = np.logspace(1, 3, num=10, base=3)

3. 列表赋值, 视图, 拷贝,三者之间的关系

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(id(a))
b = a[:]
print(id(b))
b[0] = 1024
print(a)
print(b) # 列表赋值 change

c = np.arange(0, 10)
c2 = c[:]
print(id(c))

print(id(c2))

c2[0] = 1024
print(c2)#  视图 change
print(c)# 视图 change


d = np.arange(0, 10)
d2 = d.copy()
d2[0] = 1024
print(id(d))
print(id(d2))
print(d) # 拷贝 
print(d2) # change

4. 高级索引返回数据副本, 切片返回数据视图

a = np.array([[1, 2, 3], [3, 4, 5], [4, 5, 6]])
print(a[..., 1:])
print(a[1:, 1:])

5. C风格和F风格的区别(只有在遍历的时候有区别)

array01 = np.arange(0, 20, 2)
array01 = array01.reshape([2, 5])
array02 = array01.copy(order='F')
print(array02)
# [[ 0  2  4  6  8]
#  [10 12 14 16 18]]
# 0    10    2    12    4    14    6    16    8    18    
for x in np.nditer(array02): #列优先方式输出数据
    print(x, end='\t')
print()

6. 矩阵的堆叠

# 矩阵的纵向堆叠 
# 12
# 34
# 56
# 78
np.concatenate((a,b))

# 矩阵的横向堆叠
# 1256
# 3478
np.concatenate((a,b),axis=1)

猜你喜欢

转载自www.cnblogs.com/LLWH134/p/10424450.html
今日推荐