Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Sum operation in numpy arrays

41 views
Skip to first unread message

Ana Dionísio

unread,
May 2, 2013, 5:10:11 AM5/2/13
to
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?

Jens Thoms Toerring

unread,
May 2, 2013, 6:24:13 AM5/2/13
to
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 ___ j...@toerring.de
\__________________________ http://toerring.de

Steven D'Aprano

unread,
May 2, 2013, 6:33:57 AM5/2/13
to
On Thu, 02 May 2013 02:10:11 -0700, Ana Dionísio 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]

These are not numpy arrays, they are lists of ints. Based on the error
message you quote:

TypeError: unsupported operand type(s) for +: 'float' and 'numpy.string_'"

you have at least one numpy array of floats, and one numpy array of
strings. Identify which array has got strings in it instead of floats,
then identify how it got filled with strings, and change it to fill it
with floats instead.

Start by printing this:

print(type(a), type(b), type(c))
print(type(a[0]), type(b[0]), type(c[0]))

and see what they say.


My guess is that somewhere in your code you have a list of strings:

l = ['1', '2', '3']

(perhaps because you read them from a file), and then you converted it to
a numpy array:

x = numpy.array(l)


without converting the strings to floats.


--
Steven
0 new messages