Sum operation in numpy arrays

A

Ana Dionísio

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=a+b+c

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?
 
J

Jens Thoms Toerring

Ana Dionísio said:
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=a+b+c

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
 
S

Steven D'Aprano

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top