Home > Software design >  How to construct a numpy array from a list whose each element contains row and column indices?
How to construct a numpy array from a list whose each element contains row and column indices?

Time:10-03

I have a list l whose each element is of a form [row_index, column_index, value]. Then I would like to construct a numpy array array_ from this list. This means array_[row_index, column_index] = value for [row_index, column_index, value] in l. We can generate an empty array and use loop to sequentially fill in the values. However, I think it not efficient. Could you elaborate on how to do so more efficiently?

import numpy as np
l = [[0, 0, 0.0],
     [0, 1, 14.0],
     [0, 2, 7.0],
     [1, 1, 0.0],
     [1, 2, 7.0],
     [2, 2, 0.0],
     [1, 0, 14.0],
     [2, 0, 7.0],
     [2, 1, 7.0]]
 
l

CodePudding user response:

l=np.array(l)

Simple method using numpy

CodePudding user response:

to recap, code :

import numpy as np
l = [[0, 0, 0.0],
     [0, 1, 14.0],
     [0, 2, 7.0],
     [1, 1, 0.0],
     [1, 2, 7.0],
     [2, 2, 0.0],
     [1, 0, 14.0],
     [2, 0, 7.0],
     [2, 1, 7.0]]
 
l=np.array(l)

print(l,'\n',type(l), '\n',l.size, '\n',l.shape)

output:

[[ 0.  0.  0.]
 [ 0.  1. 14.]
 [ 0.  2.  7.]
 [ 1.  1.  0.]
 [ 1.  2.  7.]
 [ 2.  2.  0.]
 [ 1.  0. 14.]
 [ 2.  0.  7.]
 [ 2.  1.  7.]] 
 <class 'numpy.ndarray'> 
 27 
 (9, 3)
  • Related