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))
  • 相关阅读:
    java 静态方法分析
    编译时常量与运行时常量
    springboot+elasticsearch配置实现
    spring+mybatise注解实现
    @RequestParam @RequestBody @PathVariable 等参数绑定注解详解
    @RequestBody 的正确使用办法
    springboot+jps+druid项目搭建
    python 源码安装
    liunx 时间ntp同步服务器
    spring 定时任务corn表达式
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9422219.html
Copyright © 2011-2022 走看看