python - numpy 基础(一)
一、ndarray的5个基本属性
| adim | 秩,即轴的数量或维度的数量 |
| shape | 数组的维度,对于n行m列的数组,shape为(n,m) |
| size | 数组的元素总数,对于n行m列的数组,元素总数为n*m |
| dtype | 数组中元素的类型,类似type()(注意了,type()是函数,.dtype是方法) |
| itemsize | 数组中每个元素的字节大小,int32类型字节为4,float64的字节为8 |
ar = np.array([[0,1,2,3,4], [9,8,7,6,5]]) print(ar.ndim) print(ar.shape) print(ar.size) print(ar.dtype) print(ar.itemsize) #运行结果 2 (2, 5) 10 int32 4
br = np.array([[[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4]], [[9,8,7,6,5],[9,8,7,6,5],[9,8,7,6,5]]]) print(br.ndim) print(br.shape) print(br.size) print(br.dtype) print(br.itemsize) #运行结果 3 (2, 3, 5) 30 int32 4
二、ndarray数组的创建
1、从列表、元组以及他们的混合类型中创建
x = np.array([0,1,2,3]) #列表 y = np.array((4,5,6,7)) #元组 z = np.array([[8,9],(10,11)]) #列表和元组混合 print(x) print(y) print(z) #运行结果 [0 1 2 3] [4 5 6 7] [[ 8 9] [10 11]]
2、使用函数创建
| np.arrange(x,y,n) | 类似range(),元素从x到y,步长为n |
| np.ones(shape,dtype) | shape是元组类型,根据shape生成一个全是1的数组 |
| np.ones_like(a) | 生成一个与数组a相同形状的全是1的数组 |
| np.zeros(shape,dtype) | shape是元组类型,根据shape生成一个全是0的数组 |
| np.zeros_like(a) | 生成一个与数组a相同形状的全是0的数组 |
| np.full(shape,val) | shape是元组类型,根据shape生成一个全是val值的数组 |
| np.full_like(a,val) | 生成一个与数组a相同形状的全是val值的数组 |
| np.eye(n) | 生成一个n阶单位矩阵数组 |
(1)np.arrange
print(np.arange(10)) # 返回0-9,整型 print(np.arange(10.0)) # 返回0.0-9.0,浮点型 print(np.arange(5,12)) # 返回5-11 print(np.arange(5.0,12,2)) # 返回5.0-12.0,步长为2 #运行结果 [0 1 2 3 4 5 6 7 8 9] [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.] [ 5 6 7 8 9 10 11] [ 5. 7. 9. 11.]
(2)np.ones 、 np.ones_like 、np.zeros 、 np.zeros_like
x = np.array([[1,2], (3,4)]) a = np.ones((2,3),dtype = np.int) #dtype指定数据类型,默认为浮点 b = np.ones_like(x) c = np.zeros((3,4)) d = np.zeros_like(x) #运行结果 [[1 1 1] [1 1 1]] [[1 1] [1 1]] [[ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]] [[0 0] [0 0]]
(3)np.full、np.full_like
a = np.full((2,3),5,dtype = np.int)
b = np.full_like(a,1) print(a)
print(b)
#运行结果 [[5 5 5] [5 5 5]]
[[1 1 1]
[1 1 1]]
(4)np.eye
a = np.eye(3,dtype = np.int) print(a) #运行结果 [[1 0 0] [0 1 0] [0 0 1]]
3、其他特殊函数创建
(1)numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, dtype=None)
参数解释:start初始值;stop结束值;num生产的样本数;endpoint是否包括结束值;retstep为真的话,返回(样本,步长)的一个元组,第一个元素是数组,第二 个元素为步长;dtype数组类型。
a1 = np.linspace(1,3,3) a2 = np.linspace(1,4,3,endpoint = False) a3 = np.linspace(1,3,3,retstep = True,dtype = np.int) print(a1) print(a2) print(a3,type(a3)) #运行结果 [ 1. 2. 3.] [ 1. 2. 3.] (array([1, 2, 3]), 1.0) <class 'tuple'>
(2)np.concatenate 将两个或多个数组合并成一个新的数组
a = np.arange(3) b = np.arange(4,6) c = np.arange(7,9) d = np.concatenate((a,b,c)) print(a) print(b) print(c) print(d) #运行结果 [0 1 2] [4 5] [7 8] [0 1 2 4 5 7 8]

浙公网安备 33010602011771号