Newer
Older
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"<img width=\"800px\" src=\"../fidle/img/00-Fidle-header-01.svg\"></img>\n",
"# <!-- TITLE --> [NP1] - A short introduction to Numpy\n",
"<!-- DESC --> Numpy is an essential tool for the Scientific Python.\n",
"<!-- AUTHOR : Jean-Luc Parouty (CNRS/SIMaP) -->\n",
"\n",
"## Objectives :\n",
" - Comprendre les grands principes de Numpy et son potentiel\n",
"\n",
"Note : This notebook is strongly inspired by the UGA Python Introduction Course \n",
"See : **https://gricad-gitlab.univ-grenoble-alpes.fr/python-uga/py-training-2017**"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"\n",
"Code using `numpy` usually starts with the import statement"
]
},
{
"cell_type": "code",
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"metadata": {},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"NumPy provides the type `np.ndarray`. Such array are multidimensionnal sequences of homogeneous elements. They can be created for example with the commands:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([10. , 12.5, 15. , 17.5, 20. ])"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# from a list\n",
"l = [10.0, 12.5, 15.0, 17.5, 20.0]\n",
"np.array(l)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 6.93990061e-310, 6.95333088e-310, -1.90019324e+120,\n",
" 6.93987701e-310])"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# fast but the values can be anything\n",
"np.empty(4)"
]
},
{
"cell_type": "code",
"execution_count": 4,
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"outputs": [
{
"data": {
"text/plain": [
"array([[0., 0., 0., 0., 0., 0.],\n",
" [0., 0., 0., 0., 0., 0.]])"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# slower than np.empty but the values are all 0.\n",
"np.zeros([2, 6])"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(2, 3, 4) 24 float64\n"
]
},
{
"data": {
"text/plain": [
"array([[[1., 1., 1., 1.],\n",
" [1., 1., 1., 1.],\n",
" [1., 1., 1., 1.]],\n",
"\n",
" [[1., 1., 1., 1.],\n",
" [1., 1., 1., 1.],\n",
" [1., 1., 1., 1.]]])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# multidimensional array\n",
"a = np.ones([2, 3, 4])\n",
"print(a.shape, a.size, a.dtype)\n",
"a"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0, 1, 2, 3])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# like range but produce 1D numpy array\n",
"np.arange(4)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0., 1., 2., 3.])"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# np.arange can produce arrays of floats\n",
"np.arange(4.)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([10. , 12.5, 15. , 17.5, 20. ])"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# another convenient function to generate 1D arrays\n",
"np.linspace(10, 20, 5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A NumPy array can be easily converted to a Python list."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[10.0, 12.5, 15.0, 17.5, 20.0]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = np.linspace(10, 20 ,5)\n",
"list(a)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[10.0, 12.5, 15.0, 17.5, 20.0]"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Or even better\n",
"a.tolist()"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"Elements in a `numpy` array can be accessed using indexing and slicing in any dimension. It also offers the same functionalities available in Fortan or Matlab.\n",
"\n",
"For example, we can create an array `A` and perform any kind of selection operations on it."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0.14726334, 0.90799321, 0.67130094, 0.23978162, 0.96444415],\n",
" [0.26039418, 0.06135763, 0.35856793, 0.73366941, 0.50698925],\n",
" [0.39557097, 0.55950866, 0.70056205, 0.65344863, 0.90891062],\n",
" [0.19049184, 0.56355734, 0.71701494, 0.66035889, 0.06400119]])"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A = np.random.random([4, 5])\n",
"A"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get the element from second line, first column\n",
"A[1, 0]"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0.14726334, 0.90799321, 0.67130094, 0.23978162, 0.96444415],\n",
" [0.26039418, 0.06135763, 0.35856793, 0.73366941, 0.50698925]])"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get the first two lines\n",
"A[:2]"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0.96444415, 0.50698925, 0.90891062, 0.06400119])"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get the last column\n",
"A[:, -1]"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0.14726334, 0.67130094, 0.96444415],\n",
" [0.26039418, 0.35856793, 0.50698925]])"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get the first two lines and the columns with an even index\n",
"A[:2, ::2]"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 2.2 - Using a mask to select elements validating a condition:"
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[False True True False True]\n",
" [False False False True True]\n",
" [False True True True True]\n",
" [False True True True False]]\n",
"[0.90799321 0.67130094 0.96444415 0.73366941 0.50698925 0.55950866\n",
" 0.70056205 0.65344863 0.90891062 0.56355734 0.71701494 0.66035889]\n"
]
}
],
"source": [
"cond = A > 0.5\n",
"print(cond)\n",
"print(A[cond])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The mask is in fact a particular case of the advanced indexing capabilities provided by NumPy. For example, it is even possible to use lists for indexing:"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0.14726334 0.90799321 0.67130094 0.23978162 0.96444415]\n",
" [0.26039418 0.06135763 0.35856793 0.73366941 0.50698925]\n",
" [0.39557097 0.55950866 0.70056205 0.65344863 0.90891062]\n",
" [0.19049184 0.56355734 0.71701494 0.66035889 0.06400119]]\n"
"array([[0.14726334, 0.90799321, 0.96444415],\n",
" [0.26039418, 0.06135763, 0.50698925],\n",
" [0.39557097, 0.55950866, 0.90891062],\n",
" [0.19049184, 0.56355734, 0.06400119]])"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Selecting only particular columns\n",
"print(A)\n",
"A[:, [0, 1, 4]]"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Step 3 - Perform array manipulations\n",
"### 3.1 - Apply arithmetic operations to whole arrays (element-wise):"
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[26.49431985, 34.90438372, 32.16365436, 27.45531142, 35.57459401],\n",
" [27.67174691, 25.61734103, 28.71425022, 32.87496493, 30.32693058],\n",
" [29.11218606, 30.9081365 , 32.49640767, 31.96148136, 34.91522467],\n",
" [26.94120557, 30.95317031, 32.68425986, 32.03966276, 25.6441081 ]])"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(A+5)**2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[1.15865904, 2.47934201, 1.95678132, 1.27097157, 2.62332907],\n",
" [1.29744141, 1.0632791 , 1.43127825, 2.08270892, 1.66028496],\n",
" [1.48523197, 1.74981253, 2.01488485, 1.92215822, 2.48161763],\n",
" [1.2098445 , 1.75691133, 2.04830976, 1.93548684, 1.06609367]])"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.exp(A) # With numpy arrays, use the functions from numpy !"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0. 0.90799321 0.67130094 0.23978162 0.96444415]\n",
" [0. 0.06135763 0.35856793 0.73366941 0.50698925]\n",
" [0. 0.55950866 0.70056205 0.65344863 0.90891062]\n",
" [0. 0.56355734 0.71701494 0.66035889 0.06400119]]\n"
]
}
],
"source": [
"A[:, 0] = 0.\n",
"print(A)"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 0. 1.10132983 1.48964487 4.17046144 1.03686668]\n",
" [ 0. 16.29789234 2.78887186 1.36301171 1.97242842]\n",
" [ 0. 1.78728245 1.42742531 1.53034219 1.1002182 ]\n",
" [ 0. 1.77444232 1.39467107 1.51432807 15.62470834]]\n"
]
}
],
"source": [
"# BONUS: Safe element-wise inverse with masks\n",
"cond = (A != 0)\n",
"A[cond] = 1./A[cond]\n",
"print(A)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Step 4 - Attributes and methods of `np.ndarray` (see the [doc](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html#numpy.ndarray))"
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"T all any argmax argmin argpartition \n",
"argsort astype base byteswap choose clip \n",
"compress conj conjugate copy ctypes cumprod \n",
"cumsum data diagonal dot dtype dump \n",
"dumps fill flags flat flatten getfield \n",
"imag item itemset itemsize max mean \n",
"min nbytes ndim newbyteorder nonzero partition \n",
"prod ptp put ravel real repeat \n",
"reshape resize round searchsorted setfield setflags \n",
"shape size sort squeeze std strides \n",
"sum swapaxes take tobytes tofile tolist \n",
"tostring trace transpose var view "
"for i,v in enumerate([s for s in dir(A) if not s.startswith('__')]):\n",
" print(f'{v:16}', end='')\n",
" if (i+1) % 6 == 0 :print('')"
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 0. 1.10132983 1.48964487 4.17046144 1.03686668]\n",
" [ 0. 16.29789234 2.78887186 1.36301171 1.97242842]\n",
" [ 0. 1.78728245 1.42742531 1.53034219 1.1002182 ]\n",
" [ 0. 1.77444232 1.39467107 1.51432807 15.62470834]]\n",
"Mean value 2.818696254398785\n",
"Mean line [0. 5.24023674 1.77515328 2.14453585 4.93355541]\n",
"Mean column [1.55966056 4.48444087 1.16905363 4.06162996]\n"
"# Ex1: Get the mean through different dimensions\n",
"print('Mean value', A.mean())\n",
"print('Mean line', A.mean(axis=0))\n",
"print('Mean column', A.mean(axis=1))"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 0. 1.10132983 1.48964487 4.17046144 1.03686668]\n",
" [ 0. 16.29789234 2.78887186 1.36301171 1.97242842]\n",
" [ 0. 1.78728245 1.42742531 1.53034219 1.1002182 ]\n",
" [ 0. 1.77444232 1.39467107 1.51432807 15.62470834]]\n",
"[ 0. 1.10132983 1.48964487 4.17046144 1.03686668 0.\n",
" 16.29789234 2.78887186 1.36301171 1.97242842 0. 1.78728245\n",
" 1.42742531 1.53034219 1.1002182 0. 1.77444232 1.39467107\n",
" 1.51432807 15.62470834] (20,)\n"
"# Ex2: Convert a 2D array in 1D keeping all elements\n",
"A_flat = A.flatten()\n",
"print(A_flat, A_flat.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]\n",
"385.0\n"
]
}
],
"source": [
"b = np.linspace(0, 10, 11)\n",
"c = b @ b\n",
"# before 3.5:\n",
"# c = b.dot(b)\n",
"print(b)\n",
"print(c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"| ` ` | Matlab | Numpy |\n",
"| ------------- | ------ | ----- |\n",
"| element wise | `.*` | `*` |\n",
"| dot product | `*` | `@` |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`numpy` arrays can also be sorted, even when they are composed of complex data if the type of the columns are explicitly stated with `dtypes`."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"\n",
"We already saw `numpy.random` to generate `numpy` arrays filled with random values. This submodule also provides functions related to distributions (Poisson, gaussian, etc.) and permutations."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To perform linear algebra with dense matrices, we can use the submodule `numpy.linalg`. For instance, in order to compute the determinant of a random matrix, we use the method `det`"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0.33277412 0.18065847 0.10352574 0.48095553 0.97748505]\n",
" [0.20756676 0.33166777 0.00808192 0.18868636 0.1722338 ]\n",
" [0.94092977 0.21755657 0.52045179 0.45008315 0.1751413 ]\n",
" [0.27404121 0.53531168 0.41209088 0.22503687 0.50026306]\n",
" [0.23077516 0.99886616 0.74286904 0.40849416 0.57970741]]\n"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A = np.random.random([5,5])\n",
"print(A)\n",
"np.linalg.det(A)"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0.33166777 0.00808192]\n",
" [0.21755657 0.52045179]]\n"
"array([[ 3.0460928 , -0.04730175],\n",
" [-1.27331197, 1.94118039]])"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"squared_subA = A[1:3, 1:3]\n",
"print(squared_subA)\n",
"np.linalg.inv(squared_subA)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### 4.4 - Introduction to Pandas: Python Data Analysis Library\n",
"\n",
"Pandas is an open source library providing high-performance, easy-to-use data structures and data analysis tools for Python.\n",
"\n",
"[Pandas tutorial](https://pandas.pydata.org/pandas-docs/stable/10min.html)\n",
"[Grenoble Python Working Session](https://github.com/iutzeler/Pres_Pandas/)\n",
"[Pandas for SQL Users](http://sergilehkyi.com/translating-sql-to-pandas/)\n",
"[Pandas Introduction Training HPC Python@UGA](https://gricad-gitlab.univ-grenoble-alpes.fr/python-uga/training-hpc/-/blob/master/ipynb/11_pandas.ipynb)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"<img width=\"80px\" src=\"../fidle/img/00-Fidle-logo-01.svg\"></img>"
}
],
"metadata": {
"celltoolbar": "Diaporama",
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",