'Filling a 2D array with values from a 1D array, but using list comprehension
I'm trying to "paste" the values contained in the 1D array dataslice (1x8) into the 2D array values_matrix (9x9), following the position indices contained in the array setup (8x2):
It's easy enough with a double for loop, but I want to be able to do this in one line using list comprehension.
However, my current code returns the error
NameError: name 'i' is not defined
referring to the "i" in if i == setup[i][0]
, so I'm obviously missing something about how this works.
import numpy as np
n = 9
setup = np.array([(3, 8),(5, 8),(4, 6),(4, 4),(2, 4),(6, 4),(3, 0),(5, 0)])
dataslice = np.array([ 1.82907198, 1.69794981, 1.30089053, -0.00452952, 2.32777365, 0.69508469, 2.06540834, 2.1184028 ])
values_matrix = np.zeros((n,n))
values_matrix = [j for i, j in (enumerate(dataslice) if i == setup[i][0] else 0)]
Could anyone tell me why I can't refer back to the "i" defined at the start of the list comprehension line later in this line?
Also, I know that I need to use nested list comprehension for the 2D "paste" operation, but I'm still in the learning phase and haven't figured that out yet, hence why my code above doesn't do this yet.
EDIT: @obchardon came up with a much better approach using indexing, I just had to adapt the "coordinates" in dataslice:
setup = np.array([(0, 3),(0, 5),(2, 4),(4, 4),(4, 2),(4, 6),(8, 3),(8, 5)])
values_matrix[setup[:,0],setup[:,1]] = dataslice
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|