samol
samol

Reputation: 20570

Faster alternative than a loop to create a numpy array

I have an array which contains point clouds (about 100 ladar points). I need to create a set of numpy arrays as quickly as possible.

sweep = np.empty(
    shape=(len(sweep.points),),
    dtype=[
        ('point', np.float64, 3),
        ('intensity', np.float32),
        ## ..... more fields ....
    ]
)

for index, point in enumerate(sweep.points):
        sweep[index]['point'] = (point.x, point.y, point.z)
        sweep[index]['intensity'] = point.intensity
        ## ....more fields...

Writing an explicit loop is very inefficient and slow. Is there a better way to go about this?

Upvotes: 0

Views: 418

Answers (1)

kuppern87
kuppern87

Reputation: 1135

It's slightly faster to use a list comprehension to format the data and pass it directly to a numpy array:

np.array([((point.x, point.y, point.z), point.intensity)
          for point in points],
         dtype=[('point', np.float64, 3),
                ('intensity', np.float32)])

Upvotes: 2

Related Questions