mcExchange
mcExchange

Reputation: 6498

Access indexed rows in a python list (similar to Matlab cell array)

I have a bunch of different matrices of different size stored on disk. I need to process them in python in a fast way so I loaded every matrix into memory and stored them in a python list. I want to select a subset of these list entries via a vector of row indices (equivalent to selecting cells in a cell array in Matlab) is that possible in python?

A Matlab example would look like this:

allData = cell(100,1); % This cell array contains my different matrices of variable sizes
rowIndices = randi(100,10,1);

selectedData = allData(rowIndices,1);

How can I do the same in python?

allData # In python this is a list of "numpy.ndarray"s
rowIndices = random.sample(range(1, numRows), batch_size)
batch_data = allData[rowIndices]

doesn't work

Upvotes: 0

Views: 89

Answers (2)

Michael J. Barber
Michael J. Barber

Reputation: 25052

A simple approach would be to use a list comprehension:

batch_data = [allData[i] for i in rowIndices]

Upvotes: 1

lig
lig

Reputation: 3890

Consider using NumPy matrix. It looks like its take() method could be helpful in this case.

Upvotes: 1

Related Questions