spule
spule

Reputation: 25

Efficient way of extracting from an array of objects

I have a an array of objects in python:

meshnodearray = ['MeshNode object', 'MeshNode object', 'MeshNode object', ...]

Where for example first 'MeshNode object' is:

({'coordinates': (15.08, 273.01, 322.61), 'instanceName': None, 'label': 1})

I need to create an array of coordinates like this:

NODEcoo = np.zeros((nnod,3),dtype='float64')
for i in meshnodearray:
    NODEcoo[i.label-1,0:] = np.array(i.coordinates)

For large arrays this is slow. Is there a more efficient way of doing this, maybe without the for loop?

Upvotes: 1

Views: 381

Answers (1)

alexis
alexis

Reputation: 50190

Try extracting the coordinates into a python list of coordinates and converting it into a numpy array in one go. If the label values are sequential from 1 to nnod, it's as simple as this:

coords = [ n['coordinates'] for n in meshnodearray ]
NODEcoo = np.array(coords)

It would be somewhat better to do this with a generator (which would let you avoid creating the intermediate array), but numpy can create only one-dimensional arrays from a generator, with numpy.fromiter().

Upvotes: 1

Related Questions