Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to python scalar

Tags:

python

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
like image 435
CharlieShe Avatar asked Feb 16 '26 13:02

CharlieShe


2 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.

like image 170
Pierre GM Avatar answered Feb 19 '26 05:02

Pierre GM


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.

like image 20
oz123 Avatar answered Feb 19 '26 05:02

oz123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!