• numpy.tile(A, reps) Construct an array by repeating A the number of times given by reps.

    tile是瓷砖的意思,顾名思义,这个函数就是把数组像瓷砖一样铺展开来。
    【例】将原矩阵横向、纵向地复制。

    1. import numpy as np
    2. x = np.array([[1, 2], [3, 4]])
    3. print(x)
    4. # [[1 2]
    5. # [3 4]]
    6. y = np.tile(x, (1, 3))
    7. print(y)
    8. # [[1 2 1 2 1 2]
    9. # [3 4 3 4 3 4]]
    10. y = np.tile(x, (3, 1))
    11. print(y)
    12. # [[1 2]
    13. # [3 4]
    14. # [1 2]
    15. # [3 4]
    16. # [1 2]
    17. # [3 4]]
    18. y = np.tile(x, (3, 3))
    19. print(y)
    20. # [[1 2 1 2 1 2]
    21. # [3 4 3 4 3 4]
    22. # [1 2 1 2 1 2]
    23. # [3 4 3 4 3 4]
    24. # [1 2 1 2 1 2]
    25. # [3 4 3 4 3 4]]
    • numpy.repeat(a, repeats, axis=None)Repeat elements of an array.
      • axis=0,沿着y轴复制,实际上增加了行数。
      • axis=1,沿着x轴复制,实际上增加了列数。
      • repeats,可以为一个数,也可以为一个矩阵。
      • axis=None时就会flatten当前矩阵,实际上就是变成了一个行向量。

    【例】重复数组的元素。

    1. import numpy as np
    2. x = np.repeat(3, 4)
    3. print(x) # [3 3 3 3]
    4. x = np.array([[1, 2], [3, 4]])
    5. y = np.repeat(x, 2)
    6. print(y)
    7. # [1 1 2 2 3 3 4 4]
    8. y = np.repeat(x, 2, axis=0)
    9. print(y)
    10. # [[1 2]
    11. # [1 2]
    12. # [3 4]
    13. # [3 4]]
    14. y = np.repeat(x, 2, axis=1)
    15. print(y)
    16. # [[1 1 2 2]
    17. # [3 3 4 4]]
    18. y = np.repeat(x, [2, 3], axis=0)
    19. print(y)
    20. # [[1 2]
    21. # [1 2]
    22. # [3 4]
    23. # [3 4]
    24. # [3 4]]
    25. y = np.repeat(x, [2, 3], axis=1)
    26. print(y)
    27. # [[1 1 2 2 2]
    28. # [3 3 4 4 4]]