fill 2d array python value from a list / 1d array

Question:

How do I fill a 2d array value from an updated 1d list ?

for example I have a list that I get from this code :

a=[]
for k, v in data.items():
     b=v/sumcount
     a.append(b)

What I want to do is produce several ‘a’ list and put their value into 2d array with different column. OR put directly the b value into 2D array whic one colum represent loop for number of k.

*My difficulties here is, k is not integer. its dict keys (str). whose length=9

I have tried this but does not work :

row  = len(data.items())
matrix=np.zeros((9,2))
for i in range (1,3) :
    a=[]
    for k, v in data.items():
        b=v/sumcount
        matrix[x][i].fill(b), for x in range (1, 10)
 

a list is

1
2
3
4
5
6
7
8
9

and for example I do the outer loop, what I expect is
*for example 1 to 2 outer loop so I expect there will be 2 column and 9 row.

1   6
2   7
3   8
4   9
5   14
6   15
7   16
8   17
9   18

I want to fill matrix value with b

Asked By: beginner

||

Answers:

To fill a 2D array with values from an updated 1D list, you can use a nested for loop. The outer loop would iterate over the columns of the 2D array, and the inner loop would iterate over the rows. For each column, you can update the list a and then use the inner loop to fill the corresponding column of the 2D array with the values from a.

Here is an example of how you could implement this:

# Initialize the 2D array with zeros
row = len(data.items())
col = 2  # Number of columns in the 2D array
matrix = np.zeros((row, col))

# Iterate over the columns of the 2D array
for i in range(col):
    # Update the list 'a'
    a = []
    for k, v in data.items():
        b = v / sumcount
        a.append(b)
    
    # Fill the current column of the 2D array with the values from 'a'
    for j in range(row):
        matrix[j][i] = a[j]

This should fill the 2D array matrix with the values from the updated 1D list a, with each column corresponding to a different iteration of the outer loop.

Answered By: Janski
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.