Newer
Older
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.sqrt(A)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.exp(A)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Other universal functions take 2 arrays as input. These are called *binary* functions.\n",
"\n",
"For example `maximum()` selects the biggest values from two input arrays"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.random.randn(10)\n",
"y = np.random.randn(10)\n",
"np.maximum(x, y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Other functions can return multiple arrays:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"A = np.random.randn(10)\n",
"A"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"remainder, whole = np.modf(A)\n",
"print(remainder)\n",
"print(whole)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is a list of most *ufuncs* in NumyPy:\n",
"*again, you don't need to memorise them. This is just a reference*\n",
"### Unary functions (accept one argument)\n",
"\n",
"| Function | Description |\n",
"|----|----|\n",
"| abs, fabs | Compute the absolute value element-wise for integer, floating point, or complex values.<br>Use fabs as a faster alternative for non-complex-valued data |\n",
"| sqrt | Compute the square root of each element. Equivalent to arr ** 0.5 |\n",
"| square | Compute the square of each element. Equivalent to arr ** 2 |\n",
"| exp | Compute the exponent ex of each element |\n",
"| log, log10, log2, log1p | Natural logarithm (base e), log base 10, log base 2, and log(1 + x), respectively |\n",
"| sign | Compute the sign of each element: 1 (positive), 0 (zero), or -1 (negative) |\n",
"| ceil | Compute the ceiling of each element, i.e. the smallest integer greater than or equal to each element |\n",
"| floor | Compute the floor of each element, i.e. the largest integer less than or equal to each element |\n",
"| rint | Round elements to the nearest integer, preserving the dtype |\n",
"| modf | Return fractional and integral parts of array as separate array |\n",
"| isnan | Return boolean array indicating whether each value is NaN (Not a Number) |\n",
"| isfinite, isinf | Return boolean array indicating whether each element is finite (non-inf, non-NaN) or infinite, respectively |\n",
"| cos, cosh, sin, sinh, tan, tanh | Regular and hyperbolic trigonometric functions |\n",
"| arccos, arccosh, arcsin,<br>arcsinh, arctan, arctanh | Inverse trigonometric functions |\n",
"| logical_not | Compute truth value of not x element-wise. Equivalent to -arr. |\n",
"\n",
"### Binary functions (accept 2 arguments)\n",
"| Functions | Description |\n",
"| ---- | ---- |\n",
"| add | Add corresponding elements in arrays |\n",
"| subtract | Subtract elements in second array from first array |\n",
"| multiply | Multiply array elements |\n",
"| divide, floor_divide | Divide or floor divide (truncating the remainder) |\n",
"| power | Raise elements in first array to powers indicated in second array |\n",
"| maximum, fmax | Element-wise maximum. fmax ignores NaN |\n",
"| minimum, fmin | Element-wise minimum. fmin ignores NaN |\n",
"| mod | Element-wise modulus (remainder of division) |\n",
"| copysign | Copy sign of values in second argument to values in first argument |\n",
"| greater, greater_equal, less,<br>less_equal, equal, not_equal |\tPerform element-wise comparison, yielding boolean array. <br>Equivalent to infix operators >, >=, <, <=, ==, != |\n",
"| logical_and, logical_or, logical_xor | Compute element-wise truth value of logical operation. Equivalent to infix operators & |, ^ |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Other useful operations <a name=\"other\"></a>\n",
"NumPy offers a set of mathematical functions that compute statistics about an entire array:"
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"B = np.random.randn(5, 4)\n",
"B"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"B.mean()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.mean(B)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"B.sum()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"B.mean(axis=1) # Compute mean in column (axis 1) direction (i.e. the mean of each row)"
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here `mean(axis=1)` means compute the mean across the columns (axis 1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is a set of other similar functions:\n",
"\n",
"| Function | Description|\n",
"| --- | --- |\n",
"|sum | Sum of all the elements in the array or along an axis. Zero-length arrays have sum 0. |\n",
"| mean | Arithmetic mean. Zero-length arrays have NaN mean. |\n",
"| std, var | Standard deviation and variance, respectively, with optional<br>degrees of freedom adjustment (default denominator n). |\n",
"|min, max | Minimum and maximum. |\n",
"| argmin, argmax | Indices of minimum and maximum elements, respectively. |\n",
"| cumsum | Cumulative sum of elements starting from 0 |\n",
"| cumprod | Cumulative product of elements starting from 1 |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There also are some boolean operations. `any` tests whether one or more values in an array is `True`, and `all` tests whether all values are `True`:"
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"A = np.random.randn(100)\n",
"A_bool = A > 0\n",
"A_bool"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"A_bool.any()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"A_bool.all()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 8\n",
"Generate and normalise a random 5x5x5 matrix"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 9\n",
"Create a random vector of size 30 and find its mean value"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 10\n",
"Subtract the mean of each row of a randomly generated matrix:"
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Sorting <a name=\"sorting\"></a>\n",
"Similar to Python's built-in list type, NumyPy arrays can be sorted in place:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"A = np.random.randn(10)\n",
"A"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"A.sort()\n",
"A"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another option is `unique()` which returns the sorted unique values in an array."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Linear Algebra <a name=\"linear\"></a>\n",
"Similar to other languages like MATLAB, NumyPy offers a set of standard linear algebra operations, like matrix multiplication, decompositions, determinants and etc.. Unlike some other languages though, the default operations like `*` peform element-wise operations. To perform matrix-wise operartions we need to use special functions:"
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"temp = np.arange(16)\n",
"A = temp[:8]\n",
"B = temp[8:]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"A.dot(B)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also extend this with the `numpy.linalg` package:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from numpy.linalg import inv, qr\n",
"A = np.random.randn(5, 5)\n",
"mat = A.T.dot(A)\n",
"mat"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"inv(mat)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mat.dot(inv(mat))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is a set of commonly used numpy.linalg functions\n",
"\n",
"| Function | Description |\n",
"| --- | --- |\n",
"| diag | Return the diagonal (or off-diagonal) elements of a square matrix as a 1D array,<br>or convert a 1D array into a square matrix with zeros on the off-diagonal |\n",
"| dot | Matrix multiplication |\n",
"| trace | Compute the sum of the diagonal elements |\n",
"| det | Compute the matrix determinant |\n",
"| eig | Compute the eigenvalues and eigenvectors of a square matrix |\n",
"| inv | Compute the inverse of a square matrix |\n",
"| pinv | Compute the Moore-Penrose pseudo-inverse inverse of a square matrix |\n",
"| qr | Compute the QR decomposition |\n",
"| svd | Compute the singular value decomposition (SVD) |\n",
"| solve | Solve the linear system Ax = b for x, where A is a square matrix |\n",
"| lstsq | Compute the least-squares solution to y = Xb |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 11\n",
"Obtain the diagonal of a dot product of 2 random matrices"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## File IO <a name=\"file\"></a>\n",
"NumPy offers its own set of File IO functions.\n",
"\n",
"The most common one is `genfromtxt()` which can load the common `.csv` and `.tsv` files.\n",
"\n",
"Now let us analyse temperature data from Stockholm over the years.\n",
"\n",
"First we have to load the file:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data = np.genfromtxt(\"./data/stockholm_td_adj.dat\")\n",
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The first column of this array gives years, and the 6th gives temperature readings. We can extract these."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"yrs = data[:, 0]\n",
"temps = data[:, 5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Having read in our data, we can now work with it - for example, we could produce a plot.\n",
"We will cover plotting in more depth in notebook 4, so there's no need to get too caught up in the details right now - this is just an examle of something we might do having read in some data. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(16, 6)) # Create a 16x6 figure\n",
"plt.plot(yrs, temps) # Plot temps vs yrs\n",
"\n",
"#Set some labels\n",
"plt.title(\"Temperatures in Stockholm\")\n",
"plt.xlabel(\"year\")\n",
"plt.ylabel(\"Temperature (C)\")\n",
"\n",
"plt.show() # Show the plot"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise 12\n",
"Read in the file `daily_gas_price.csv`, which lists the daily price of natural gas since 1997. Each row contains a date and a price, separated by a comma. Find the minimum, maximum, and mean gas price over the dataset.\n",
"\n",
"(Hint: you will need to use the delimiter option in `np.genfromtxt` to specify that data is separated by commas. Also, NumPy will interpret the data in float format by default - we may need to set the dtype to a string format at first, then discard the dates, before turning the gas prices back into floats to process them! Otherwise, NumPy may find it confusing to try and interpret dates formatted as YYYY-MM-DD as floats and will probably complain.)"
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"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",