numpy之数组创建

# coding=utf-8
import  numpy as np
import  random
############一维数组创建#############
#方式一
t1 = np.array([1,2,3],dtype=float)
print(t1,t1.dtype,t1.shape)

#方式二
t2 = np.array(range(5),dtype=float)
print(t2,t2.dtype,t2.shape)

#方式三
t3 = np.arange(10).astype(float)
print(t3,t3.dtype,t3.shape)

#方式四--->生成小数数据
t4 = np.array([random.random() for i in range(6)])
t4 = np.round(t4,2)  #round取两位小数
print(t4,t4.dtype,t4.shape)

#方式五 --->将多维矩阵转为一维,将属性行和列相乘
t = np.array([[1,2,3],[4,5,6]],dtype=float)
t = t.reshape((t.shape[1]*t.shape[0]))
print(t,t.dtype,t.shape)
print("*"*10)

#方式六(建议使用这种方式将多维转为一维)
t = np.array([[1,2,3],[4,5,6]],dtype=float)
t = t.flatten()
print(t,t.dtype,t.shape)

#############创建多维数组##############
#方式一 --->创建全为0的3行4列矩阵
t5 = np.zeros((3,4),dtype=float)
print(t5,t5.dtype,t5.shape)

#方式二 -->创建全为1的3行4列矩阵
t6 = np.ones((3,4),dtype=float)
print(t6,t6.dtype,t6.shape)

#方式3 --->创建对角线为1的3行3列矩阵
t7 = np.eye(3)
print(t7,t7.dtype,t7.shape)

#方式4 --->通过reshape()可以将一维或多维转换其他维度矩阵
t8 = np.arange(10).reshape((2,5))
print(t8,t8.dtype,t8.shape)

'''
多维数组:
    (2,3,4):2表示两块数据,3表示一块数据为3行,4表示一行数据为4列数据
    注意只看reshape()最后两位数,最前面的数据表示数据块
'''

猜你喜欢

转载自www.cnblogs.com/ywjfx/p/10827036.html