zoukankan      html  css  js  c++  java
  • numpy 辨异(四)—— np.repeat 与 np.tile

    >> import numpy as np
    >> help(np.repeat)
    >> help(np.tile)
    • 二者执行的是均是复制操作;
    • np.repeat:复制的是多维数组的每一个元素
    • np.tile:复制的是多维数组本身

    1. np.repeat

    >> x = np.arange(1, 5).reshape(2, 2)
    >> np.repeat(x, 2)
    array([1, 1, 2, 2, 3, 3, 4, 4])
            # 对数组中的每一个元素进行复制
            # 除了待重复的数组之外,只有一个额外的参数时,高维数组也会 flatten 至一维

    当然将高维 flatten 至一维,并非经常使用的操作,也即更经常地我们在某一轴上进行复制,比如在行的方向上(axis=1),在列的方向上(axis=0):

    >> np.repeat(x, 3, axis=1)
    array([[1, 1, 1, 2, 2, 2],
           [3, 3, 3, 4, 4, 4]])
    >> np.repeat(x, 3, axis=0)
    array([[1, 2],
           [1, 2],
           [1, 2],
           [3, 4],
           [3, 4],
           [3, 4]])

    当然更为灵活地也可以在某一轴的方向上(axis=0/1),对不同的行/列复制不同的次数:

    >> np.repeat(x, (2, 1), axis=0)
    array([[1, 2],
           [1, 2],
           [3, 4]])
    >> np.repeat(x, (2, 1), axis=1)
    array([[1, 1, 2],
           [3, 3, 4]])

    2. np.tile

    Python numpy 下的 np.tile有些类似于 matlab 中的 repmat函数。不需要 axis 关键字参数,仅通过第二个参数便可指定在各个轴上的复制倍数。

    >> a = np.arange(3)
    >> np.tile(a, 2)
    array([0, 1, 2, 0, 1, 2])
    >> np.tile(a, (2, 2))
    array([[0, 1, 2, 0, 1, 2],
           [0, 1, 2, 0, 1, 2]])
    
    >> b = np.arange(1, 5).reshape(2, 2)
    >> np.tile(b, 2)
    array([[1, 2, 1, 2],
           [3, 4, 3, 4]])
    
    # 等价于
    >> np.tile(b, (1, 2))
  • 相关阅读:
    WebAPI实现移动端上传头像接口
    WebAPI发布IIS报错问题
    EF 解除属性映射到数据库中 NotMappedAttribute无效解决办法
    更改MVC注册Areas的顺序,掌控Areas的运作
    js判断字符串是否为JSON格式
    docker commit命令
    强大的strace命令用法详解
    Openshift概念
    如何在生产环境使用Btrace进行调试
    kill-9 kill-15
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9422219.html
Copyright © 2011-2022 走看看