numpy之 np.repeat 与 np.tile

2022-10-04 10:29:31

numpy之 np.repeat 与 np.tile

numpy数组扩展函数有repeat和tile,由于数组不能进行动态扩展,故函数调用之后都重新分配新的空间来存储扩展后的数据。

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

np.repeat

repeat函数功能:对数组中的元素进行连续重复复制

用法有两种:

1) numpy.repeat(a, repeats, axis=None)

2) a.repeats(repeats, axis=None)

其中a为数组,repeats为重复的次数,axis表示数组维度

行的方向上(axis=1),在列的方向上(axis=0)

# -*- coding: utf-8 -*-
import numpy as np
a = np.arange(10)
print(a)
print("\n")
print(a.repeat(5))
print("\n")
a=np.array([10,20])
print(a.repeat([3,2]))
print("\n")
x = np.arange(1, 5).reshape(2, 2)
print(np.repeat(x, 3, axis=1))
print("\n")
print(np.repeat(x, 3, axis=0))
print("\n")
print(np.repeat(x, (2, 1), axis=0))
print("\n")
print(np.repeat(x, (2, 1), axis=1))

输出结果

[0 1 2 3 4 5 6 7 8 9]


[0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 6 6 6 6 7 7
 7 7 7 8 8 8 8 8 9 9 9 9 9]


[10 10 10 20 20]


[[1 1 1 2 2 2]
 [3 3 3 4 4 4]]


[[1 2]
 [1 2]
 [1 2]
 [3 4]
 [3 4]
 [3 4]]


[[1 2]
 [1 2]
 [3 4]]


[[1 1 2]
 [3 3 4]]

np.tile

tile函数功能:对整个数组进行复制拼接

用法:numpy.tile(a, reps)

其中a为数组,reps为重复的次数

不需要 axis 关键字参数,仅通过第二个参数便可指定在各个轴上的复制倍数。

# -*- coding: utf-8 -*-
import numpy as np
a = np.arange(10)
print(a)
print("\n")
print(np.tile(a,2))
print("\n")
print(np.tile(a,(3,2)))
print("\n")
a = np.arange(10).reshape(2,5)
print(np.tile(a,2))
print("\n")
print(np.tile(a,(3,2)))
print("\n")

输出结果

[0 1 2 3 4 5 6 7 8 9]


[0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9]


[[0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9]
 [0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9]
 [0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9]]


[[0 1 2 3 4 0 1 2 3 4]
 [5 6 7 8 9 5 6 7 8 9]]



---------------------
作者:Inside_Zhang
来源:CSDN
原文:https://blog.csdn.net/lanchunhui/article/details/56017472
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 作者:路易三十六
  • 原文链接:https://blog.csdn.net/LuYi_WeiLin/article/details/85269580
    更新时间:2022-10-04 10:29:31