首頁>Program>source
import numpy as np
data = np.arange(-50,50,10)
print data
[-50 -40 -30 -20 -10   0  10  20  30  40]

我要重複資料的每个元素5次並按如下所示製作新陣列:

ans = [-50 -50 -50 -50 -50 -40 -40 ... 40]

我该怎麼办?

將整个陣列重複5次怎麼樣?

ans =  [-50 -40 -30 -20 -10   0  10  20  30  40 -50 -40 -30 -20 -10   0  10  20  30  40 -50 -40 -30 -20 -10   0  10  20  30  40 -50 -40 -30 -20 -10   0  10  20  30  40 -50 -40 -30 -20 -10   0  10  20  30  40 .......]
最新回復
  • 5月前
    1 #

    In [1]: data = np.arange(-50,50,10)
    

    要重複每个元素5次,請使用np.repeat:

    In [3]: np.repeat(data, 5)
    Out[3]: 
    array([-50, -50, -50, -50, -50, -40, -40, -40, -40, -40, -30, -30, -30,
           -30, -30, -20, -20, -20, -20, -20, -10, -10, -10, -10, -10,   0,
             0,   0,   0,   0,  10,  10,  10,  10,  10,  20,  20,  20,  20,
            20,  30,  30,  30,  30,  30,  40,  40,  40,  40,  40])
    

    要重複陣列5次,請使用np.tile:

    In [2]: np.tile(data, 5)
    Out[2]: 
    array([-50, -40, -30, -20, -10,   0,  10,  20,  30,  40, -50, -40, -30,
           -20, -10,   0,  10,  20,  30,  40, -50, -40, -30, -20, -10,   0,
            10,  20,  30,  40, -50, -40, -30, -20, -10,   0,  10,  20,  30,
            40, -50, -40, -30, -20, -10,   0,  10,  20,  30,  40])
    

    但是,請註意,有時您可以利用NumPy廣播,而不用建立具有重複元素的更大陣列.

    例如,如果

    z = np.array([1, 2])
    v = np.array([[3], [4], [5]])
    

    然後添加這些陣列以产生

    [[4 5]
      [5 6]
      [6 7]]
    

    您不需要使用圖塊:

    In [12]: np.tile(z, (3,1))
    Out[12]: 
    array([[1, 2],
           [1, 2],
           [1, 2]])
    In [13]: np.tile(v, (1,2))
    Out[13]: 
    array([[3, 3],
           [4, 4],
           [5, 5]])
    In [14]: np.tile(z, (3,1)) + np.tile(v, (1,2))
    Out[14]: 
    array([[4, 5],
           [5, 6],
           [6, 7]])
    

    相反,NumPy將為您廣播陣列:

    In [15]: z + v
    Out[15]: 
    array([[4, 5],
           [5, 6],
           [6, 7]])
    

  • 5月前
    2 #

    只需使用 np.repeat

    In [5]: data.repeat(5)
    Out[5]: 
    array([-50, -50, -50, -50, -50, -40, -40, -40, -40, -40, -30, -30, -30,
           -30, -30, -20, -20, -20, -20, -20, -10, -10, -10, -10, -10,   0,
             0,   0,   0,   0,  10,  10,  10,  10,  10,  20,  20,  20,  20,
            20,  30,  30,  30,  30,  30,  40,  40,  40,  40,  40])
    

  • ivy:解釋如何使用檔案系統解析器的樣本示例
  • 在SQL Server中建立审核觸發器