# 1.2 - Intro to Numpy

Last updated: February 16th, 2019

# Intro to Numpy - Exercises¶

In [ ]:
import numpy as np

### Exercise 1¶

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

In [ ]:

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)

### Exercise 2¶

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

In [ ]:
In [ ]:
np.array([0, 1, 2, 3, 4], dtype=np.float)
In [ ]:
np.arange(0, 4, dtype=np.float)

### Exercise 3¶

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

In [ ]:
a = np.array([1, 9, 9, 9, 11])
In [ ]:
In [ ]:
a[0] + a[-1]

### Exercise 4¶

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

In [ ]:
a = np.arange(5, 16)
a
In [ ]:
In [ ]:
a.sum()

### 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 [ ]:
In [ ]:
arr = np.array([
l0,
l1,
l2,
l3,
l4,
l5,
l6
])
arr

### Exercise 6¶

With the previously created array:

In [ ]:
In [ ]:
arr[0, 0]

In [ ]:
In [ ]:
arr[-1, 0]

### Exercise 7¶

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

GDP
1785387
2833687
3874437
2167744
4602367
2950039
17348075
In [ ]:
In [ ]:
arr[:, 1]

### Exercise 8¶

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

In [ ]:
In [ ]:
gdp_per_capita = arr[:, 1] / arr[:, 0]
In [ ]:
gdp_per_capita

### 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 [ ]: