1

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?

3
  • If you have to do that for all objects in the array then I see no other way. Commented May 5, 2012 at 11:26
  • Yes I need to do this for all the objects. Commented May 5, 2012 at 16:54
  • list comprehensions will do then. Commented May 5, 2012 at 17:18

1 Answer 1

1

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().

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

1 Comment

Thanks, this is a little faster. Could this be done maybe in parallel to further speed it up?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.