np.array数组的维度及数据读取

数据的维度关系,

import numpy as np
x = np.array([1, 2, 3, 4])#一维列向量
print(x,x.shape)#[1 2 3 4] (4,), .shape 尺度 (n,m)
print(x.size)#.size 数组对象的元素个数 n*m=4
print(x.ndim)#.ndm 维度=1

y = np.array([[1, 2, 3, 4]])#二维横向量
print(y,y.shape)#[[1 2 3 4]] (1, 4)
print(y.size)#.size 数组对象的元素个数 n*m
print(y.ndim)#.ndm 维度=2

z=np.array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
      [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
      [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
print(z,z.shape)#[[1 2 3 4]] (1, 4)
print(z.size)#.size 数组对象的元素个数 n*m
print(z.ndim)#.ndm 维度=2

z3=np.array([[[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
      [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
      [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]]])
print('pp',z3)#
print('oo',z3.shape)
print(z3.size)#24
print(z3.ndim)#3

#########################################
#下面的是比较奇怪的,原因还不知道
##########################################
z2=np.array([[[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
      [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
      [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]],[[1,2,3]]])
print('pp',z2)#[[1 2 3 4]] (1, 4)
print('oo',z2.shape)
print(z2.size)#2
print(z2.ndim)#1,可以看出这里进

数组中元素的读取,按照索引

import numpy as np
a = np.array([0,1, 2, 3, 4,5])#一维列向量
print(a[3:5])  # [3,4],用范围作为下标获取数组的一个切片,包括a[3]不包括a[5]
print(a[:4])   # [0 1 2 3],省略开始下标,表示从a[0]开始,取4个元素
print(a[:-2])  # [0 1 2 3]下标可以使用负数,表示从a[0]开始,取到从数组后往前数的第2个元素为止(但不包含第2个元素)
b = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8])
print(b[2:4])#[2 3]

对于多维的数组

import numpy as np
a = np.array([[1, 2, 3],[4,5,6]])#一维列向量
print(a.shape)#(2, 3)
for i in range(a.shape[0]):#对a的每行进行遍历
   print(a[i, :2])#取每行的前2个元素[1 2]  [4 5]

猜你喜欢

转载自blog.csdn.net/weixin_38145317/article/details/89946051