import numpy as np
# 多维切片
def ndarry_demo():
# 多维矩阵 切片
# matrix[start1:stop1, start2:stop2]
x = np.array([[1,2,3],[4,5,6]], np.int32)
print(type(x))
print(x.shape)
print(x.dtype)
print(x[1,2])
print(x)
# 取第一行 全部列 注意逗号
print(x[1,:])
# 取全部行 第一列
print(x[:,1])
print(x.size)
print(x.real)
# 数组迭代
def iterator_demo():
y = np.array([3,2,5,6,9,5,8,0])
# for e in y:
# print(e)
# 0-6的数字重塑为两行三列数组
z = np.arange(6).reshape(2,3)
print(z)
# 按照行访问多维数组
for e in np.nditer(z,order='C'):
print(e)
# 按照列访问多维数组
for e in np.nditer(z, order='F'):
print(e)
# 打开读写标志op_flags=['readwrite']
with np.nditer(z,op_flags = ['readwrite']) as it:
for e in it:
# [...]在NumPy中通常用于多维索引,允许你访问或修改数组的子集可以直接使用 e = 2* e
e[...] = 2 * e
print(e)
# %d用于格式化十进制整数。%s用于格式化字符串
a = np.arange(6).reshape(2, 3)
# 输出行索引
it = np.nditer(a,flags=['c_index'])
# while not是当条件为假的情况下执行代码块 条件为真的情况下跳过代码块
while not it.finished:
print("%d <%d>" % (it.value, it.index),end=' ')
it.iternext()
print('\n')
# 输出多维索引
b = np.arange(6).reshape(2, 3)
im = np.nditer(b, flags=['multi_index'])
while not im.finished:
print("%d <%s>" % (im.value, im.multi_index), end=' ')
im.iternext()
if __name__ == '__main__':
# ndarry_demo()
iterator_demo()
Numpy库学习-多维切片、单数组迭代
最新推荐文章于 2024-10-15 10:20:47 发布