Basic array operations - SOLVED#

All arithmetic operators on numpy arrays apply elementwise.

Elementwise operations are really powerful and we will be using them a lot!!! Let’s illustrate this with some examples:

import numpy as np # run this cell or the numpy commands won't run
array1 = np.array([10, 20, 13])
array2 = np.arange(3)
print(f"array1 is {array1}, array2 is {array2}")
print("The (elementwise) sum of these two arrays")
print(array1 + array2)
print("The (elementwise) difference of these two arrays")
print(array1 - array2)
array1 is [10 20 13], array2 is [0 1 2]
The (elementwise) sum of these two arrays
[10 21 15]
The (elementwise) difference of these two arrays
[10 19 11]

We can take the (elementwise) products:

print("The (elementwise) product of these two arrays")
print(array1 * array2)
The (elementwise) product of these two arrays
[ 0 20 26]

Do you see what this is doing?? Rather than having to loop over both arrays and multiply, or add, each pair of element together, we can do all of it in one command.

So:

array_3 = array_1 * array_2

Using numpy arrays is the same as doing:

array_3 = []
for idx in range(len(array_1)):
    array_3.append(array_1[idx] * array_2[idx])

Which of the above is easier to read and quicker to write?

You can also do things like:

array_1 = array_1 * 3

or even

array_1 *= 3

to multiply all values of array_1 by 3, rather than having to use a for loop for this.

Exercise 2.1#

In the cell below create two numpy arrays of the same size. One array should be created either by using np.arange or np.linspace. Then add and subtruct them together (element-wise). Print the resulting arrays.

array_one = np.linspace(2,5,10)
array_two = np.arange(1,2,0.1)
array_three = array_one + array_two
array_four = array_one - array_two

print(array_three)
print(array_four)
[3.         3.43333333 3.86666667 4.3        4.73333333 5.16666667
 5.6        6.03333333 6.46666667 6.9       ]
[1.         1.23333333 1.46666667 1.7        1.93333333 2.16666667
 2.4        2.63333333 2.86666667 3.1       ]

Exercise 2.2#

In the cell below create one array by using np.linspace, it should contain 5 equally spaced points in the interval \([0, 1]\) (so the first value should be 0, and the last value 1). Then raise this array to the power of three (element-wise) (ie. compute value**3 for all values in the array). Print the resulting array. Then repeat the process but raise the array to the power of two (element-wise).

new_array = np.linspace(0,1,5)
print(new_array)

cubed_array = new_array**3
print(cubed_array)

squared_array = new_array**2
print(squared_array)
[0.   0.25 0.5  0.75 1.  ]
[0.       0.015625 0.125    0.421875 1.      ]
[0.     0.0625 0.25   0.5625 1.    ]

Special functions#

We can use numpy mathematical functions to compute things like sin or the square root directly on all elements of an array, no loops required!

array1 = np.linspace(0,4,20)

print("The (elementwise) square root of array1 is")
print(np.sqrt(array1))
print("The (elementwise) exp of array1 is")
print(np.exp(array1))
print("The (elementwise) sin of array1 is")
print(np.sin(array1))
The (elementwise) square root of array1 is
[0.         0.45883147 0.64888568 0.79471941 0.91766294 1.02597835
 1.12390297 1.21395396 1.29777137 1.3764944  1.4509525  1.52177182
 1.58943883 1.65434038 1.71679015 1.77704663 1.83532587 1.89181061
 1.94665705 2.        ]
The (elementwise) exp of array1 is
[ 1.          1.23432754  1.52356446  1.88057757  2.32124868  2.86518116
  3.53657199  4.36528819  5.38819541  6.65079796  8.20926306 10.13291944
 12.50734147 15.43815597 19.055741   23.52102582 29.03264982 35.83579909
 44.23311356 54.59815003]
The (elementwise) sin of array1 is
[ 0.          0.20897462  0.40872137  0.59041986  0.74604665  0.86872962
  0.95305133  0.99528832  0.9935755   0.9479885   0.86054034  0.73509255
  0.57718464  0.39378948  0.19300541 -0.01630136 -0.2248883  -0.42354465
 -0.60349817 -0.7568025 ]

Exercise 2.3#

In the cell below create an array of \(100\) equally spaced points from the interval \([0,10]\). Then print the array that contains the values of the function \(\cos\) evaluated on all points of this array.

###Example:
If we have an array of \([0, 1, 2]\) then the array that contains the values of the function \(\cos\) evaluated at this array is \([\cos(0), \cos(1), \cos(2)]\).

narray = np.linspace(0.,10.,100)
print(np.cos(narray))
[ 1.          0.99490282  0.97966323  0.95443659  0.91948007  0.87515004
  0.8218984   0.76026803  0.69088721  0.61446323  0.53177518  0.44366602
  0.35103397  0.25482335  0.15601496  0.0556161  -0.04534973 -0.14585325
 -0.24486989 -0.34139023 -0.43443032 -0.52304166 -0.60632092 -0.68341913
 -0.75355031 -0.81599952 -0.87013012 -0.91539031 -0.95131866 -0.97754893
 -0.9938137  -0.99994717 -0.9958868  -0.981674   -0.95745366 -0.92347268
 -0.88007748 -0.82771044 -0.76690542 -0.69828229 -0.6225406  -0.54045251
 -0.45285485 -0.36064061 -0.26474988 -0.16616018 -0.06587659  0.03507857
  0.13567613  0.23489055  0.33171042  0.4251487   0.51425287  0.59811455
  0.67587883  0.74675295  0.8100144   0.86501827  0.91120382  0.94810022
  0.97533134  0.99261957  0.99978867  0.99676556  0.98358105  0.96036956
  0.9273677   0.88491192  0.83343502  0.77346177  0.70560358  0.63055219
  0.54907273  0.46199582  0.37020915  0.27464844  0.17628785  0.07613012
 -0.0248037  -0.12548467 -0.2248864  -0.32199555 -0.41582217 -0.50540974
 -0.58984498 -0.66826712 -0.7398767  -0.8039437  -0.859815   -0.90692104
 -0.94478159 -0.97301068 -0.99132055 -0.99952453 -0.99753899 -0.98538417
 -0.96318398 -0.93116473 -0.88965286 -0.83907153]

Other important functions (including some from statistics)#

The sum#

array_for_stats = np.array([3.4, 5.6, 7.8])
print("The sum of the above array is")
print(np.sum(array_for_stats))
print("or equivalently")
print(array_for_stats.sum())
The sum of the above array is
16.8
or equivalently
16.8

Exercise 2.4#

In the cell below, create an array of the first 100 positive integers. Then print its sum.

pint_array = np.arange(1,101)
print(sum(pint_array))
5050

Then print its mean.

print("The mean of the above array is")
print(np.mean(pint_array))
print("or equivalently")
print(array_for_stats.mean())
The mean of the above array is
50.5
or equivalently
5.6000000000000005

Exercise 2.5#

In the cell below, create an array of 10 numbers (floats). Then print their mean.

f_array = np.linspace(0.1,4.5,10)
a_mean = np.mean(f_array)
print(f"The mean of the above array is {a_mean}")
The mean of the above array is 2.3

The standard deviation

print("The standard deviation of the above array is")
print(np.std(array_for_stats))
print("or equivalently")
print(array_for_stats.std())
The standard deviation of the above array is
1.7962924780409972
or equivalently
1.7962924780409972

Exercise 2.7#

In the cell below, create an array of 100 ones. Then calculate its standard deviation. Do you know why the standard deviation is equal to \(0\)?

array_of_many_ones = np.ones(100)
sdev = np.std(array_of_many_ones)

print(sdev)

print(f"""The standard deviation of an array in which each element is identical
is {sdev}.
This is becase there is no scatter or variation from the mean value.""")
0.0
The standard deviation of an array in which each element is identical
is 0.0.
This is becase there is no scatter or variation from the mean value.

The largest (maximum) element of an array#

print("The maximum of the above array is")
print(np.max(array_for_stats))
print("or equivalently")
print(array_for_stats.max())
The maximum of the above array is
7.8
or equivalently
7.8

Exercise 2.8#

In the cell below create two arrays

  • first one having the elements [3.14, 6.28, 12.56].

  • second one having the elements [2.72, 6.81, 20.43].

Divide the first array by the second array (element-wise), then find the maximum of the resulting array.

my_array_one = np.array([3.14, 6.28, 12.56])
my_array_two = np.array([2.72, 6.81, 20.43])
my_array_three = my_array_one/my_array_two

my_max = np.max(my_array_three)
print(f"The maximum of the resulting array is {my_max}")
The maximum of the resulting array is 1.1544117647058822

The lowest (minimum) element of an array#

print("The minimum of the above array is")
print(np.min(array_for_stats))
print("or equivalently")
print(array_for_stats.min())
The minimum of the above array is
3.4
or equivalently
3.4

Exercise 2.9#

In the cell below create two arrays

  • first one having the elements [3.14, 2.28, 4.26].

  • second one having the elements [1.72, 2.81, 0.43].

Multiply the first array by the second array (element-wise), then find the minimum of the resulting array.

a1 = np.array([3.14, 2.28, 4.26])
a2 = np.array([1.72, 2.81, 0.43])
a3 = a1*a2

print(np.min(a3))
1.8317999999999999

Rounding an array#

array_lots_decim = np.array([2.33333333333, 3.555555555, 6.88685756464])
n = 2
print(f"Rounding to {n} decimal places")
print(np.round(array_lots_decim, n))
Rounding to 2 decimal places
[2.33 3.56 6.89]

Exercise 2.10#

In the cell below create 17 equally spaced points from the interval [0, 1]. Round the elements of the array to 3 decimal places and print the rounded array.

spaced_array = np.linspace(0,1,17)
n = 3
print(f"Rounding to {n} decimal places.")
print(np.round(spaced_array,n))
Rounding to 3 decimal places.
[0.    0.062 0.125 0.188 0.25  0.312 0.375 0.438 0.5   0.562 0.625 0.688
 0.75  0.812 0.875 0.938 1.   ]