Sum operation in numpy arrays

Jens Thoms Toerring jt at toerring.de
Thu May 2 06:24:13 EDT 2013


Ana Dionísio <anadionisio257 at gmail.com> wrote:
> Hello! I have several numpy arrays in my script and i want to add them. For example:

> a=[1,2,3,4,5]
> b=[1,1,1,1,1]
> c=[1,0,1,0,1]

> for i in range(5):
>     d[i]=a[i]+b[i]+c[i]

> print d

> [3,3,5,5,7]

> I did it like that but I get an error: "TypeError: unsupported operand type(s) for +: 'float' and 'numpy.string_'"

> How can I sum my arrays?

There's no numpy array at all in use in your example program, you
only have normal lists. If you had numpy arrays you wouldn't need
to loop over the indivindual elements, you could do just

d = a + b + c

to add up the (numpy) arrays.

The error message you get may indicate that somewhere in your real
code (not the one you posted) one of the elements of one of the
(numpy) arrays is not a number but a string, e.g. by doing some-
thing like

a = numpy.array( [ 1, '2', 3, 4, 5 ] )

(note the single quotes around 2, that will result in the element
having a type of 'numpy.string'. But if it's like that is impossible
to tell without seeing the real code you're using;-) I guess you
will have to give us what you actually use if you want something
more helpful.
                            Regards, Jens
-- 
  \   Jens Thoms Toerring  ___      jt at toerring.de
   \__________________________      http://toerring.de



More information about the Python-list mailing list