簡體   English   中英

迭代 numpy arrays 並格式化為多維 arrays

[英]Iterating numpy arrays and formatting into multi dimensional arrays

我正在嘗試編寫一個 numpy function 代碼,它將下面的Appending_list function 組織為Values的每次迭代的多維數組。 因此,在第一次迭代中,第一行是Number_array + 0 ,第二行是Number_array + 1 ,第三行是Number_array + 2

import numpy as np
from numpy import random
Values = np.arange(0,3,1)
Number_array =  np.arange(1,5,1)
Appending_list = Number_array + Values * len(Number_array)

預計 Output

[[1,2,3,4], [2,3,4,5], [3,4,5,6]]
values = np.arange(1, 5)
rows = 3
# creates 3 rows of `[1, 2, 3, 4]`
result = np.tile(values, rows).reshape((rows, len(values)))
shifts = np.arange(3)
# shifts the row values for each row by 0, 1, and 2 respectively
result += shifts[:,None]

結果

array([[1, 2, 3, 4],
       [2, 3, 4, 5],
       [3, 4, 5, 6]])

您正在研究廣播:

Appending_list = Number_array + Values[:,None]

Output:

array([[1, 2, 3, 4],
       [2, 3, 4, 5],
       [3, 4, 5, 6]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM