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))
  • 相关阅读:
    SQL之merge into(转)
    SQL Server 中的 NOLOCK 到底是什么意思?
    SSIS之数据流任务
    SSIS之序列容器
    SSIS的控制流之Foreach循环容器和序列容器
    SSIS的控制流之For循环容器
    SSIS包的组建之连接管理器
    SSIS包的开发
    SSIS简介
    ODBC、OLE DB、 ADO的区别
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9422219.html
Copyright © 2011-2022 走看看