Transform List into Numpy Matrix

Transform List into Numpy Matrix

I have a matrix X and a list centres. I want to create a new numpy matrix td_X.

I want to populate td_X with the which is made up of the rows of X where the index is equal to centres. In pseudocode:

for each in centers:
  td_X.append(X[eacj])

How can I do this using Python?

1

2 Answers

Since that middle dimension is size 1, just reshape or squeeze it.

x = np.array(alist)
x = np.squeeze(x)  # or
x = x.reshape(45, 5785)  # or
x = x[:,0,:]

You can remove the extra layer of nesting in the list, but this kind of reshaping is so much easier with arrays.

From x[0], you have an extra level of list wrapped around. Removing it by indexing should get you there:

x = np.array([l[0] for l in x])

Here is a small example:

x = [[[1,2]], [[2,3]], [[4,5]]]

np.array(x).shape
# (3, 1, 2)

np.array([l[0] for l in x]).shape
# (3, 2)

np.array([l[0] for l in x])
# array([[1, 2],
#        [2, 3],
#        [4, 5]])
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.