2

I have an array X of <class 'scipy.sparse.csr.csr_matrix'> format with shape (44, 4095)

I would like to now to create a new numpy array say X_train = np.empty([44, 4095]) and copy row by row in a different order. Say I want the 5th row of X in 1st row of X_train.

How do I do this (copying an entire row into a new numpy array) similar to matlab?

2 Answers 2

6

Define the new row order as a list of indices, then define X_train using integer indexing:

row_order = [4, ...]
X_train = X[row_order]

Note that unlike Matlab, Python uses 0-based indexing, so the 5th row has index 4.

Also note that integer indexing (due to its ability to select values in arbitrary order) returns a copy of the original NumPy array.

This works equally well for sparse matrices and NumPy arrays.

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

Comments

0

Python works generally by reference, which is something you should keep in mind. What you need to do is make a copy and then swap. I have written a demo function which swaps rows.

import numpy as np # import numpy

''' Function which swaps rowA with rowB '''
def swapRows(myArray, rowA, rowB):
    temp = myArray[rowA,:].copy() # create a temporary variable 
    myArray[rowA,:] = myArray[rowB,:].copy() 
    myArray[rowB,:]= temp

a = np.arange(30) # generate demo data
a = a.reshape(6,5) # reshape the data into 6x5 matrix

print a # prin the matrix before the swap
swapRows(a,0,1) # swap the rows
print a # print the matrix after the swap

To answer your question, one solution would be to use

X_train = np.empty([44, 4095])
X_train[0,:] = x[4,:].copy() # store in the 1st row the 5th one 

unutbu answer seems to be the most logical.

Kind Regards,

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.