|
477 | 477 | "outputs": [], |
478 | 478 | "source": [ |
479 | 479 | "Z = np.dot(np.ones((5,3)), np.ones((3,2)))\n", |
480 | | - "print(Z)", |
481 | | - "\n\n", |
| 480 | + "print(Z)\n", |
| 481 | + "\n", |
482 | 482 | "# Alternative solution, in Python 3.5 and above\n", |
483 | 483 | "Z = np.ones((5,3)) @ np.ones((3,2))" |
484 | 484 | ] |
|
628 | 628 | "source": [ |
629 | 629 | "# Suicide mode on\n", |
630 | 630 | "defaults = np.seterr(all=\"ignore\")\n", |
631 | | - "Z = np.ones(1)/0\n", |
| 631 | + "Z = np.ones(1) / 0\n", |
632 | 632 | "\n", |
633 | 633 | "# Back to sanity\n", |
634 | | - "_ = np.seterr(**defaults)" |
| 634 | + "_ = np.seterr(**defaults)\n", |
| 635 | + "\n", |
| 636 | + "An equivalent way, with a context manager:\n", |
| 637 | + "\n", |
| 638 | + "```python\n", |
| 639 | + "with np.errstate(divide='ignore'):\n", |
| 640 | + " Z = np.ones(1) / 0" |
635 | 641 | ] |
636 | 642 | }, |
637 | 643 | { |
|
1439 | 1445 | "outputs": [], |
1440 | 1446 | "source": [ |
1441 | 1447 | "A = np.random.randint(0,10,(3,4,3,4))\n", |
1442 | | - "# solution by passing a tuple of axes (introduced in numpy 1.7.0)\n", |
1443 | | - "sum = A.sum(axis=(-2,-1))\n", |
1444 | | - "print(sum)\n", |
1445 | | - "# solution by flattening the last two dimensions into one\n", |
1446 | | - "# (useful for functions that don't accept tuples for axis argument)\n", |
| 1448 | + "# solution by passing a tuple of axes (introduced in numpy 1.7.0)\n", |
| 1449 | + "sum = A.sum(axis=(-2,-1))\n", |
| 1450 | + "print(sum)\n", |
| 1451 | + "# solution by flattening the last two dimensions into one\n", |
| 1452 | + "# (useful for functions that don't accept tuples for axis argument)\n", |
1447 | 1453 | "sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)\n", |
1448 | 1454 | "print(sum)" |
1449 | 1455 | ] |
|
1471 | 1477 | "D_counts = np.bincount(S)\n", |
1472 | 1478 | "D_means = D_sums / D_counts\n", |
1473 | 1479 | "print(D_means)\n", |
1474 | | - "\n", |
| 1480 | + "\n", |
1475 | 1481 | "# Pandas solution as a reference due to more intuitive code\n", |
1476 | 1482 | "import pandas as pd\n", |
1477 | 1483 | "print(pd.Series(D).groupby(S).mean())" |
|
2334 | 2340 | "name": "python", |
2335 | 2341 | "nbconvert_exporter": "python", |
2336 | 2342 | "pygments_lexer": "ipython3", |
2337 | | - "version": "3.5.2" |
| 2343 | + "version": "3.5.1" |
2338 | 2344 | } |
2339 | 2345 | }, |
2340 | 2346 | "nbformat": 4, |
|
0 commit comments