Seoyeon Hong
Seoyeon Hong

Reputation: 593

Simple adding two arrays using numpy in python?

This might be a simple question. However, I wanted to get some clarifications of how the following code works.

a = np.arange(8)
a
array([1,2,3,4,5,6,7])
Example Function = a[0:-1]+a[1:]/2.0

In the Example Function, I want to draw your attention to the plus sign between the array a[0:-1]+a[1:]. How does that work? What does that look like?

For instance, is the plus sign (addition) adding the first index of each array? (e.g 1+2) or add everything together? (e.g 1+2+2+3+3+4+4+5+5+6+6+7)

Then, I assume /2.0 is just dividing it by 2...

Upvotes: 7

Views: 59532

Answers (2)

Taras Vaskiv
Taras Vaskiv

Reputation: 2401

If arrays have identical shapes, they can be added:

new_array = first_array.__add__(second_array)

This simple operation adds each value from first_array to each value in second_array and puts result into new_array.

Upvotes: 1

Chinny84
Chinny84

Reputation: 966

A numpy array uses vector algebra in that you can only add two arrays if they have the same dimensions as you are adding element by element

 a = [1,2,3,4,5]
 b = [1,1,1]
 a+b # will throw an error

whilst

 a = [1,2,3,4,5]
 b = [1,1,1,1,1]
 a+b # is ok

The division is also element by element.

Now to your question about the indexing

 a      = [1,2,3,4,5]
 a[0:-1]= [1,2,3,4]
 a[1:]  = [2,3,4,5]

or more generally a[index_start: index_end] is inclusive at the start_index but exclusive at the end_index - unless you are given a a[start_index:]where it includes everything up to and including the last element.

My final tip is just to try and play around with the structures - there is no harm in trying different things, the computer will not explode with a wrong value here or there. Unless you trying to do so of course.

Upvotes: 10

Related Questions