>> import numpy as np
>> help(np.repeat)
>> help(np.tile)
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]])
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))
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。