Python中的Numpy模块(1,numpy创建)

1.什么是Numpy?

     Numpy   (Numeric Python) 

    Numpy系统是Python中的一种开源的数值计算扩展。

       (1)   一个强大的N维数组对象Array

        (2)   比较成熟的(广播) 函数库

        (3)   用于整合C/C++和fortran 代码的工具包

         (4)   实用的线性代数,傅里叶变换和随机数生成函数

        (5) numpy和稀疏矩阵运算包scipy配合使用更加强大

2.使用Numpy创建numpy数组

# 导入numpy模块
import numpy as np

# 查看numpy的版本号
print(np.__version__)

# 创建ndarray
n1 = np.array([3, 1, 4, 5])  # 一维的
print(n1)
# 结果  [3 1 4 5]

n2 = np.array([[5, 1, 2, 6], [7, 9, 6, 45], [1, 5, 4, 6]])  # 二维的
print(n2)
# 结果  [[ 5  1  2  6]
#       [ 7  9  6 45]
#       [ 1  5  4  6]]

# 打印出维度
print(n1.shape)  # (4,)  四行 没有列
print(n2.shape)  # (2, 4)   三行四列

#str类型array
n3 = np.array(list('hello'))
print(n3)   #['h' 'e' 'l' 'l' 'o']
print(type(n3))

# 如果传进来的列表中包含不同的类型,则统一为同一类型,优先级:str->float->int
n4 = np.array([1,3.14,'python'])
print(n4)

3.使用Nunpy的routines创建

# 1.通过ones  (内容全是1)
# np.ones(shape,dtype=None)
# 参数说明:  shape:维度,类型是元素类型  dtype:类型
n1 = np.ones(shape=(10, 8), dtype=int)  # 二维的类型为int
print(n1)

# 三维的类型为float
n2 = np.ones(shape=(100, 80, 3), dtype=float)
print(n2)

# 2.通过zeros   (内容全是0)
# np.zeros(shape,dtype=None)

n3 = np.zeros((4, 4))  # 里面可以直接写参数值
print(n3)

# 3.通过 full   (内容全是fill_value的值)
# np.full(shape,fill_value,dtype=None)
n4 = np.full((10, 10), fill_value=1024)
print(n4)

# 4.通过 eye   (根据参数值:N行N列,并且矩阵对角线的值为1,其他的位置上的值为0)
# np.eye(N,M=None,k=0,dtype=float)
n5 = np.eye(10)  # 10行10列,对角线为1,其他位置为0   (即一元十次方程,满秩矩阵)
print(n5)

# 5.通过 linspace   (内容全是fill_value的值)
# np.linspace(start,stop,num=50,endpoint=True,retstep=False,dtype=None)
# 参数说明: 从start开始到stop结束,均匀划分num个数
n6 = np.linspace(0, 100, 50)
print(n6)

# 6.通过arange()
n7 = np.arange(0, 100, 20)  # 从0到100(左闭右开)  ,步长为2
print(n7)

# 7.1通过random.randint()   随机生成数
#  从0开始到150之间随机生成size个数,(也是左闭右开)
n8 = np.random.randint(0,150,size=5)
print(n8)
# 7.2random.randn()标准的正太分布
n9 = np.random.randn(100)
print(n9)
# 7.3random.normal()标准的分布
#  loc 代表锚点,即位置    scale代表在loc上下波动的系数,数值越大波动的越厉害
n10 = np.random.normal(loc=175,scale= 2,size=100)
print(n10)
#  7.4random.random()  生成0到1的随机数,左闭右开
n11 = np.random.random(size= (200,300,3))   #(200,300,3)代表维度
print(n11)

    

猜你喜欢

转载自blog.csdn.net/wei18791957243/article/details/83752649