1.数组创建及基本属性
import numpy as np
a = np.array([1, 2, 3], dtype = np.int64)#定义数组输出类型,np.float64
print (a)
b = np.array([[1,2,3],[4,5,6]])
print (b.shape,b.ndim,b.size)#输出b的维度:2行3列 ;b的秩:2维,即2个轴; b的数组元素个数:6个
c = b.reshape(3,2)#重新定义b的维度为3行2列
print (c)
# 数组的 dtype 为 int8(一个字节)
x = np.array([1, 2, 3, 4, 5], dtype=np.int8)
print(x.itemsize) #输出数组中每个元素的字节大小
# 数组的 dtype 现在为 float64(八个字节)
y = np.array([1, 2, 3, 4, 5], dtype=np.float64)
print(y.itemsize)
#创建数组:numpy.empty(shape, dtype = float, order = 'C')
z = np.empty([3,2], dtype = int)
print (z)
2.numpy.asarray 类似 numpy.array,但 numpy.asarray 参数只有三个,比 numpy.array 少两个。
numpy.asarray(a, dtype = None, order = None)
import numpy as np
x = [1, 2, 3]
m = np.asarray(x) #将列表转换为 ndarray:
x = (1,2,3)
n = np.asarray(x) #将元组转换为 ndarray:
x = [(1,2,3),(4,5)]
p = np.asarray(x) #将元组列表转换为 ndarray:
print(m,n,p) #结果:m:[1 2 3] n: [1 2 3] p: [(1, 2, 3) (4, 5)]
3.NumPy 从数值范围创建数组
import numpy as np
x = np.arange(10,dtype = int) #数组元素:【0,1,2,3,4~9】,其中dtype可选字段
y = np.arange(10,20,2) #10开始,20终止,步长为2,默认为1
a = np.linspace(1,10,10) #1开始,10终止,共10个等差数列
b = np.logspace(0,9,10,base=2) #起始:base ** start,即2^0 终止:base ** stop ,2^9次 共10个等比数列,以2为底
s = slice(2,7,2) # 切片:从索引 2 开始到索引 7 停止,间隔为2
s2 = x[2:7:2] # 从索引 2 开始到索引 7 停止,间隔为 2
s3 = x[2:] #表示从该索引开始以后的所有项都将被提取,输出结果[2 3 4 5 6 7 8 9]
s4 = x[2:5] #提取两个索引(不包括停止索引)之间的项。 输出结果[2 3 4]
print (x)
print(y)
print(a,b)
print (x[s]) #输出结果为:[2 4 6]
print(s2) #输出结果为:[2 4 6]
print(s3)
print(s4)
4.三角函数
import numpy as np
a = np.array([0, 30, 45, 60, 90])
print('不同角度的正弦值:')
# 通过乘 pi/180 转化为弧度
print(np.sin(a * np.pi / 180))
print('\n')
print('数组中角度的余弦值:')
print(np.cos(a * np.pi / 180))
print('\n')
print('数组中角度的正切值:')
print(np.tan(a * np.pi / 180))
5.随机数
import numpy as np
a = np.random.rand(5, 2)#返回一组给定维度的随机值,范围在【0,1)之间
b = np.random.randint(2,20,10)#生成【2-20)半开半闭区间的10个随机整数
c = np.random.random_integers(2,22,10)#生成【2-20】闭区间的10个随机整数
d = np.random.random()#生成【0-1)之间的10个随机浮点数
print(a,b,c,d)