Convert array to python scalar

Question:

I need big help, please check out this code:

import.math

dose =20.0
a = [[[2,3,4],[5,8,9],[12,56,32]]
     [[25,36,45][21,65,987][21,58,89]]
     [[78,21,98],[54,36,78],[23,12,36]]]
PAC = math.exp(-dose*a)

this what I would like to do. However the error I am getting is

TypeError: only length-1 arrays can be converted to Python scalars
Asked By: CharlieShe

||

Answers:

If you want to perform mathematical operations on arrays (whatever their dimensions…), you should really consider using NumPy which is designed just for that. In your case, the corresponding NumPy command would be:

PAC = numpy.exp(-dose*np.array(a))

If NumPy is not an option, you’ll have to loop on each element of a, compute your math.exp, store the result in a list… Really cumbersome and inefficient. That’s because the math functions require a scalar as input (as the exception told you), when you’re passing a list (of lists). You can combine all the loops in a single list comprehension, though:

PAC = [[[math.exp(-dose*j) for j in elem] for elem in row] for row in a]

but once again, I would strongly recommend NumPy.

Answered By: Pierre GM

If you want, for each element of the array to have it multiplied by -dose then apply math.exp on the result, you need a loop :

new_a = []
for subarray in a:
    new_sub_array = []
    for element in sub_array:
        new_element = math.exp(-dose*element)
        new_sub_array.append(new_element)
    new_a.append(new_sub_array)

Alternatvely, if you have a mathlab background, you could inquire numpy, that enable transformations on array.

Answered By: LBarret

You should really use NumPy for that.
And here is how you should do it using nested loops:

>>> for item in a:
...     for sub in item:
...         for idx, number in enumerate(sub): 
...             print number, math.exp(-dose*number)
...             sub[idx] = math.exp(-dose*number)

Using append is slow, because every time you copy the previous array and stack the new item to it.
Using enumerate, changes numbers in place. If you want to keep a copy of a, do:

 acopy = a[:]

If you don’t have much numbers, and NumPy is an over kill, the above could be done a tiny bit faster using list comprehensions.

Answered By: oz123
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.