Try simple arithmetic elementwise operations: add even elementswith odd elementsTime them against their pure python counterparts using %timeit.Generate:<2**0, 2**1, 2**2, 2**3, 2**4>a_j = 2^(3*j) - j

Warning

The transposition is a view

As a results, the following code is wrong and will not make amatrix symmetric :

Note

Linear algebra

The sub-module numpy.linalg implements basic linear algebra, such assolving linear systems, singular value decomposition, etc. However, it isnot guaranteed to be compiled using efficient routines, and thus werecommend the use of scipy.linalg, as detailed in sectionLinear algebra operations: scipy.linalg

Look at the help for np.allclose. When might this be useful?Look at the help for np.triu and np.tril.

You are watching:

Operands could not be broadcast together with shapes Sum by rows and by columns:

Given there is a sum, what other function might you expect to see?What is the difference between sum and cumsum?

Worked Example: data statistics

Data in populations.txtdescribes the populations of hares and lynxes (and carrots) in northernCanada during 20 years.

You can view the data in an editor, or alternatively in IPython (both shell and notebook):

The mean populations over time:

Worked Example: diffusion using a random walk algorithm

Tip

Let us consider a simple 1D random walk process: at each time step awalker jumps right or left with equal probability.

We are interested in finding the typical distance from the origin of arandom walker after t left or right jumps? We are going tosimulate many “walkers” to find this law, and we are going to do sousing array computing tricks: we are going to create a 2D array withthe “stories” (each walker has a story) in one direction, and thetime in the other:

We find a well-known result in physics: the RMS distance grows as thesquare root of the time!

1.3.2.3. Broadcasting¶ Basic operations on numpy arrays (addition, etc.) are elementwise

This works on arrays of the same size.

The image below gives an example of broadcasting:

Let’s verify:

Tip

Broadcasting seems a bit magical, but it is actually quite natural touse it when we want to solve a problem whose output data is an arraywith more dimensions than input data.

Worked Example: Broadcasting

Let’s construct an array of distances (in miles) between cities ofRoute 66: Chicago, Springfield, Saint-Louis, Tulsa, Oklahoma City,Amarillo, Santa Fe, Albuquerque, Flagstaff and Los Angeles.

A lot of grid-based or network-based problems can also usebroadcasting. For instance, if we want to compute the distance fromthe origin of points on a 10x10 grid, we can do

Remark : the numpy.ogrid function allows to directly create vectors xand y of the previous example, with two “significant dimensions”:

Tip

So, np.ogrid is very useful as soon as we have to handlecomputations on a grid. On the other hand, np.mgrid directlyprovides matrices full of indices for cases where we can’t (or don’twant to) benefit from broadcasting:

1.3.2.4.3. Adding a dimension¶ Indexing with the np.newaxis object allows us to add an axis to an array(you have seen this already above in the broadcasting section):

Exercise: Shape manipulations

Look at the docstring for reshape, especially the notes section whichhas some more information about copies and views.Use flatten as an alternative to ravel. What is the difference?(Hint: check which one returns a view and which a copy)Experiment with transpose for dimension shuffling. Try both in-place and out-of-place sorting.Try creating arrays with different dtypes and sorting them.Use all or array_equal to check the results.Look at np.random.shuffle for a way to create sortable input quicker.Combine ravel, sort and reshape.Look at the axis keyword for sort and rewrite the previousexercise.1.3.2.6. Summary¶ What do you need to know to get started?

Know how to create arrays : array, arange, ones,zeros.

Know the shape of the array with array.shape, then use slicingto obtain different views of the array: array<::2>,etc. Adjust the shape of the array using reshape or flatten itwith ravel.

Obtain a subset of the elements of an array and/or modify their valueswith masks

Know miscellaneous operations on arrays, such as finding the mean or max(array.max(), array.mean()). No need to retain everything, buthave the reflex to search in the documentation (online docs,help(), lookfor())!!

For advanced use: master the indexing with arrays of integers, as well asbroadcasting. Know more Numpy functions to handle various arrayoperations.

Quick read

If you want to do a first quick pass through the Scipy lectures tolearn the ecosystem, you can directly skip to the next chapter:Matplotlib: plotting . See more: Calvin Harris Slide Album - Slide (Calvin Harris Song)

The remainder of this chapter is not necessary to follow the rest ofthe intro part. But be sure to come back and finish this chapter, aswell as to do some more exercices .

Table Of Contents 1.3.2. Numerical operations on arrays1.3.2.1. Elementwise operations1.3.2.2. Basic reductions1.3.2.4. Array shape manipulation