Python: speed of conversion of type of 3d matrix element

Question:

I believe that this is simple question, but I’m new to Python so any suggestion will be appreciated.
I have matrix of strings, and I need to convert every element into float type and then to increase it for some number. I did that like this:

for i in range(0,len(matrix)):
    for j in range(0,len(matrix[i])):
        for k in range(0,len(matrix[j])):
            matrix[i][j][k] = float(matrix[i][j][k]) + 5.555

Is there any other way of doing this in order to increase speed? Performance is really low when I have matrix[50][50][50] or bigger.
Is there one-line method that could increase all elements at once?

Asked By: Aleksandar

||

Answers:

There are low level optimisations that you can make to your code, such as moving the calls to range() outside of the loops so you are not creating a new list (or generator if you are using 3.x) every time round the loops.

However the big optimisation is to switch to using numpy, which will execute operations across the entire array in high performance C code.

Answered By: Dave Kirby

Whenever you’re doing array work in Python, it’s best to use the numpy library if possible.

import numpy

matrix = numpy.asarray(matrix,dtype=numpy.float64) + 5.555
Answered By: rprospero

If matrix is compatible, then you could (and probably should) put it in a numpy array. It’s a very handy library for numeric computations and comes with lots of functions: depending on what you want to do, you may also want to look at scipy.

import numpy as np

a = np.array(matrix)
a += 5.5555

Given some random data as an example:

from numpy.random import random_sample

>>> a = random_sample( (3, 3, 3) )
>>> a
array([[[ 0.98899266,  0.10761687,  0.7784259 ],
        [ 0.79253918,  0.450742  ,  0.46417501],
        [ 0.71733034,  0.26575819,  0.19360072]],

       [[ 0.41609296,  0.96195897,  0.32777537],
        [ 0.59527144,  0.96655918,  0.50073892],
        [ 0.70797323,  0.406036  ,  0.47092251]],

       [[ 0.8572665 ,  0.00076713,  0.25379833],
        [ 0.03426925,  0.59837259,  0.85390736],
        [ 0.78306972,  0.00238982,  0.28702393]]])
>>> a += 5.55555
>>> a
array([[[ 6.54454266,  5.66316687,  6.3339759 ],
        [ 6.34808918,  6.006292  ,  6.01972501],
        [ 6.27288034,  5.82130819,  5.74915072]],

       [[ 5.97164296,  6.51750897,  5.88332537],
        [ 6.15082144,  6.52210918,  6.05628892],
        [ 6.26352323,  5.961586  ,  6.02647251]],

       [[ 6.4128165 ,  5.55631713,  5.80934833],
        [ 5.58981925,  6.15392259,  6.40945736],
        [ 6.33861972,  5.55793982,  5.84257393]]])
Answered By: Jon Clements