简体   繁体   中英

Iterating numpy arrays and formatting into multi dimensional arrays

I am trying code a numpy function where it organizes the Appending_list function below to a multi dimensional array for each iteration of Values . So in the first iteration is Number_array + 0 for the first row and the second row is Number_array + 1 and the third is 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)

Expected 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]

Result

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

You are looking into broadcasting:

Appending_list = Number_array + Values[:,None]

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM