Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Matrix to List of List and then Numpy Array

I want to construct a matrix like:

    Col1 Col2 Col3 Coln
row1  1    2    4    2     
row2  3    8    3    3
row3  8    7    7    3
rown  n    n    n    n

I have yet to find anything in the python documentation that states how a list of list is assembled, is it like:

a = [[1,2,4,2],[3,8,3,3],[8,7,7,3],[n,n,n,n]]

Where each row is a list item or should it be that each column is a list item:

b = [[1,3,8,n],[2,8,7,n],[4,3,7,n],[2,3,3,n]]

I would think that this would be a common question but I can't seem to find a straight answer.

Based on the documentation I'm guessing that I can convert this to a numpy array by simply:

np.array(a)

Can anyone help?

like image 814
secumind Avatar asked Dec 11 '25 07:12

secumind


2 Answers

You want the first version:

a = [[1,2,4,2],[3,8,3,3],[8,7,7,3],[n,n,n,n]]

When accessing an element in a matrix, you typically use matrix[row][col], so with the above Python list format a[i] would give you row i, and a[i][j] would give you the jth element from the ith row.

To convert it to a numpy array, np.array(a) is the correct method.

like image 154
Andrew Clark Avatar answered Dec 13 '25 21:12

Andrew Clark


This: a = [[1,2,4,2],[3,8,3,3],[8,7,7,3],[n,n,n,n]] will create the list you want, and yes, np.array(a) will convert it to a numpy array.

Also, this is the 'pythonish' was of creating an array with m rows and n columns (and setting all the elements to 0):

a = [[0 for i in range(n)] for j in range(m)]

like image 26
Ionut Hulub Avatar answered Dec 13 '25 21:12

Ionut Hulub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!