2

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
  • 1
    Did you try anything at all??? even np.array(x)??? Commented Jan 3, 2017 at 0:04

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 Comments

This still produces an array with dimensions: (45, 1, 5785)
Did you assign the result back to x?
No to a different variable.
That's interesting. I just added a small but similar example. Seems to work as expected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.