Numpy基本数据操作
(1)基本对象为N维数组对象
(2)赋值
#导入numpy
import numpy as np
#用列表赋值
#Ⅰ. 1维:
list1 = [1,3,6] #1维
s = np.array(list1)
#s = np.array(list1,dtype=int) #指定元素类型为int
print(s.shape) #查看结构
#Ⅱ. 2维
list2 = [[1,5,8],[3,6,9]] #2维
s = np.array(l)
#s = np.array(list2,dtype=int) #指定元素类型为int
print(s.shape) #查看结构
#Ⅲ. 特殊矩阵
# 0矩阵
np.zeros((3,4)) # 用元组(3,4)生成3行4列的0矩阵
np.zeros([3,4]) # 用列表[3,4]生成3行4列的0矩阵。同上
# 1矩阵
np.ones((3,4)) # 用元组(3,4)生成3行4列的元素为1的矩阵
np.ones([3,4]) # 用元组(3,4)生成3行4列的元素为1的矩阵。同上
# 等值矩阵
np.full((3,4),99) # 元素值全为99的3x4矩阵
# 单位阵
np.eye(10) # 10x10的单位阵
# 随机数组
np.random.random(3) #元素个数为3的一维随机数组
np.random.random([3,4]) #3x4矩阵,值随机
#用arange()方法赋值
np.arange(1,10,1,dtype=int)
np.linespace(1,10,10,dtype=int)
np.logspace(1,10,10,base=2) #幂次/对数赋值。此处未1到10的平方赋值
(3)取值
①切片
#连续切片
d = np.random.random([3,4])
d1 = d[0:1,2:3] #连续切片 第0行到第1行,第2列到第3列
#间隔取值
d = np.random.random(10)
d1 = d[::3] #隔3个数取1个数
d2 = d[2::3] #从第下标为2的元素开始,没隔3个数取1个数
#注意冒号位置不同可能会造成取值为单个元素或列表
#用其他序列做索引来取值
n = np.array([1,3,4))
d1 = d[n] #用n序列的元素值为索引取目标d序列相应位置上的值
#条件取值
d[d>10] #取大于10的所有元素