Numpy库学习-多维切片、单数组迭代

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值