Bart
Bart

Reputation: 123

Accessing elements of arrays within an array

Example:

matrix = np.zeros((2, 2), dtype=np.ndarray)
matrix[0, 0] = np.array([1, 2])
matrix[0, 1] = np.array([3, 4])
matrix[1, 0] = np.array([5, 6])
matrix[1, 1] = np.array([7, 8])

I would like to create a matrix from the left entries of each array, i.e.

[[1, 3], [5, 7]]

Is there a shorthand way of doing this? I have tried matrix[:,:][0] but this doesn't yield what I want...

Any help would be much appreciated!

Upvotes: 0

Views: 61

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53029

Here are a few options, slowest to fastest.

>>> import operator as op
>>> import itertools as it
>>>
>>> np.rec.fromrecords(matrix)['f0']
array([[1, 2],
       [5, 6]])
>>> timeit(lambda:np.rec.fromrecords(matrix)['f0'], number=100_000)
5.490952266845852
>>> 
>>> np.vectorize(op.itemgetter(0), otypes=(int,))(matrix)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.vectorize(op.itemgetter(0), otypes=(int,))(matrix), number=100_000)
1.1551978620700538
>>>
>>> np.stack(matrix.ravel())[:,0].reshape(matrix.shape)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda: np.stack(matrix.ravel())[:,0].reshape(matrix.shape), number=100_000)
0.9197127181105316
>>> 
>>> np.reshape(next(zip(*matrix.reshape(-1))), matrix.shape)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.reshape(next(zip(*matrix.reshape(-1))), matrix.shape), number=100_000)
0.7601758309174329
>>>
>>> np.fromiter(it.chain.from_iterable(matrix.reshape(-1)), int)[::2].reshape(matrix.shape)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.fromiter(it.chain.from_iterable(matrix.reshape(-1)), int)[::2].reshape(matrix.shape), number=100_000)
0.5561180629301816
>>> 
>>> np.frompyfunc(op.itemgetter(0), 1, 1)(matrix).astype(int)array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.frompyfunc(op.itemgetter(0), 1, 1)(matrix).astype(int), number=100_000)
0.2731688329949975
>>> 
>>> np.array(matrix.tolist())[...,0]
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.array(matrix.tolist())[...,0], number=100_000)
0.249452771153301

You may get different rank order for other problem sizes or platforms.

Upvotes: 1

Masoud
Masoud

Reputation: 1280

You can use for-loop:

import numpy as np

matrix = np.zeros((2, 2), dtype=np.ndarray)
matrix[0, 0] = np.array([1, 2])
matrix[0, 1] = np.array([3, 4])
matrix[1, 0] = np.array([5, 6])
matrix[1, 1] = np.array([7, 8])

array = [[matrix[i,j][0] for j in range(2)] for i in range(2)]

result: [[1, 3], [5, 7]]

Upvotes: 0

Related Questions