python - Optimal extraction of columns from numpy matrix -
say have numpy matrix so:
[[ x1, x2, x3, ... ], [ y1, y2, y3, ... ], [ z1, z2, z3, ... ], [ 1, 1, 1, ... ]]
from want extract list of lists so:
[[x1, y1, z1], [x2, y2, z2], [x3, y3, z3], ... ]
what optimal way of doing this?
at moment have:
tpoints = [pt[:3].tolist() pt in numpy.asarray(tptmat.t)]
and call tolist()
taking disproportionate amount of time, approximately third of time spent in time consuming function of program.
ncalls tottime percall cumtime percall filename:lineno(function) 14422540 69.777 0.000 69.777 0.000 {method 'tolist' of 'numpy.ndarray' objects} 20 64.258 3.213 178.057 8.903 trans.py:152(_apply) ...
why not remove last row before transpose?
m[:3].t.tolist() # ^^^^^^^^^ optional
micro-benchmark shows method faster yours 61%, , if don't convert list of list 45 times faster, 100×4 matrix.
$ python2.5 -m timeit -s 'import numpy; m = numpy.matrix([[5]*100,[6]*100,[7]*100,[1]*100])' 'm[:3].t' 100000 loops, best of 3: 6.26 usec per loop $ python2.5 -m timeit -s 'import numpy; m = numpy.matrix([[5]*100,[6]*100,[7]*100,[1]*100])' 'm[:3].t.tolist()' 10000 loops, best of 3: 180 usec per loop $ python2.5 -m timeit -s 'import numpy; m = numpy.matrix([[5]*100,[6]*100,[7]*100,[1]*100])' 'numpy.asarray(m[:3].t)' 100000 loops, best of 3: 10.9 usec per loop $ python2.5 -m timeit -s 'import numpy; m = numpy.matrix([[5]*100,[6]*100,[7]*100,[1]*100])' '[p[:3].tolist()for p in numpy.asarray(m.t)]' 1000 loops, best of 3: 289 usec per loop
Comments
Post a Comment