numpy数组创建以及属性

it2026-10-01  1

二、numpy

import numpy as np #创建数组 #创建一维数组 newlist = [1,2,3] print('列表',newlist) print(type(newlist)) arr1=np.array(newlist) print('数组',arr1) print(type(arr1)) arr1 = np.random.rand(3,4) # # rand如果不指定任何参数,返回的是一个浮点数(小数),指定参数就是指定数组的大小 #创建多维数组 arr1 = np.random.uniform(5,10,size=(4,4,5)) #szie中数据的个数就是数组的维度个数 #三维数组中有4个二维数组,每个二维数组中有4个一维数组,每个一维数组中有5个数据 # uniform如果不指定参数,存在默认的数据区间0-1,返回的是一个浮点数 arr1 = np.random.randint(-1,20,(4,4)) arr2 = np.random.randint(-1,552147483648,(4,4),'int64') #randint可以指定数组的区间、大小、数据类型 arr1=np.array([[1,2,3],[4,5,6]],np.int32) #最基础的定义序列数组,以及类型 arr1=np.zeros((3,4)) # 全为0数组,括号中是维度大小 arr1=np.ones((3,4)) # #全为1数组 arr2=np.arange(1,13,1) # #与定义列表相同,起始,结束,步长,可定义数据类型,创建的是一维数组 arr1=arr2.reshape(3,4) print(arr1) # print(arr2) #数组三要素 print('维度的个数',arr1.ndim) print('维度的大小',arr1.shape) print('数据类型',arr1.dtype) # print('数据类型',arr2.dtype) # 通过列表来创建数组 arr2 = np.array([1,2,3,4,'asd123']) # print('数组维度的个数',arr2.ndim) # print('数组的维度大小',arr2.shape) # print('数据类型',arr2.dtype) 注意点: 1、np.array(list,type)

数组的属性

import numpy as np arr2 = np.array([1,2,3,4,'asd123']) print('数组维度的个数',arr2.ndim) print('数组的维度大小',arr2.shape) print('数据类型',arr2.dtype)

调整数组的维度大小

def reshape(self, shape, *shapes, order='C'): # known case numpy.core.multiarray.ndarray.reshape """ a.reshape(shape, order='C') Returns an array containing the same data with a new shape. 使用: arr2 = np.array([3,4,5,6,7,8]).reshape(2,3) print(arr2) 结果:二维数组,含有两个一维数组,每个一维数组有三个元素 [[3 4 5] [6 7 8]] 注意点: 1、旧的数组的元素个数与新数组的元素个数必须相同 2、reshape这个方法存在返回值,返回新数组
最新回复(0)