Profile picture

1.2 - Intro to Numpy

Last updated: February 16th, 20192019-02-16Project preview

rmotr


Intro to Numpy - Exercises

In [ ]:
import numpy as np

green-divider

Exercise 1

Using NumPy, create an array with the first 5 numbers, starting from 0 (from 0 to 4):

In [ ]:
# your code goes here

You can try using the np.array construct, or np.arange.

In [ ]:
np.arange?
In [ ]:
np.array([0, 1, 2, 3, 4])
In [ ]:
np.arange(0, 5)

green-divider

Exercise 2

Create an array with the first 5 numbers, but set its data type to a float:

In [ ]:
# your code goes here
In [ ]:
np.array([0, 1, 2, 3, 4], dtype=np.float)
In [ ]:
np.arange(0, 4, dtype=np.float)

green-divider

Exercise 3

From the array a, sum the first and the last element:

In [ ]:
a = np.array([1, 9, 9, 9, 11])
In [ ]:
# your code goes here
In [ ]:
a[0] + a[-1]

green-divider

Exercise 4

Given the array a, return the sum of all its numbers:

In [ ]:
a = np.arange(5, 16)
a
In [ ]:
# your code goes here
In [ ]:
a.sum()

green-divider

Exercise 5

Create an array arr that represents the table displayed below. The table contains country data:

- Population GDP Surface Area HDI
0 35.467 1785387 9984670 0.913
1 63.951 2833687 640679 0.888
2 80.940 3874437 357114 0.916
3 60.665 2167744 301336 0.873
4 127.061 4602367 377930 0.891
5 64.511 2950039 242495 0.907
6 318.523 17348075 9525067 0.915

For simplicity, you can find the numbers below as lists:

In [ ]:
l0 = [35.467, 1785387, 9984670,  0.913]
l1 = [63.951, 2833687, 640679,  0.888]
l2 = [80.940, 3874437, 357114,  0.916]
l3 = [60.665, 2167744, 301336,  0.873]
l4 = [127.061, 4602367, 377930,  0.891]
l5 = [64.511, 2950039, 242495,  0.907]
l6 = [318.523, 17348075, 9525067,  0.915]
In [ ]:
# your code goes here
In [ ]:
arr = np.array([
    l0,
    l1,
    l2,
    l3,
    l4,
    l5,
    l6
])
arr

green-divider

Exercise 6

With the previously created array:

a) Print the population of the first country

In [ ]:
# your code goes here
In [ ]:
arr[0, 0]

b) Print the population of the last country

In [ ]:
# your code goes here
In [ ]:
arr[-1, 0]

green-divider

Exercise 7

From the array arr, extract the column (vector) of GDP:

GDP
1785387
2833687
3874437
2167744
4602367
2950039
17348075
In [ ]:
# your code goes here
In [ ]:
arr[:, 1]

green-divider

Exercise 8

Create a new array named gdp_per_capita containing "GDP per capita", the result of the vector GDP / Population:

In [ ]:
# your code goes here
In [ ]:
gdp_per_capita = arr[:, 1] / arr[:, 0]
In [ ]:
gdp_per_capita

green-divider

Exercise 9

Surface area is expressed in square kilometers (km²). Create a new array surface_miles to express it in squared miles mi². The conversion between km² and mi² is approximately: mi² = km² * 0.39

In [ ]:
# your code goes here
In [ ]:
surface_miles = arr[:, 2] * .39
In [ ]:
surface_miles

purple-divider

Notebooks AI
Notebooks AI Profile20060