Skip to content

Commit 5fc4971

Browse files
committed
NumPy
1 parent fb4924c commit 5fc4971

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

README.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1449,6 +1449,73 @@ with PyCallGraph(output=graph):
14491449
```
14501450

14511451

1452+
NumPy
1453+
-----
1454+
**Array manipulation mini language. Can run up to 100 times faster than equivalent Python code.**
1455+
```python
1456+
<array> = np.array(<list>)
1457+
<array> = np.ones(<shape>)
1458+
<array> = np.arange(from_inclusive, to_exclusive, step)
1459+
<array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
1460+
```
1461+
1462+
```python
1463+
value = <array>.min([axis]) # 0: columns, 1: rows
1464+
index = <array>.argmin([axis])
1465+
```
1466+
1467+
```python
1468+
<view> = <array>.reshape(<shape>)
1469+
<view> = np.broadcast_to(<array>, <shape>)
1470+
<array> = <array>[filter_expression]
1471+
```
1472+
1473+
### Broadcasting
1474+
**Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions:**
1475+
```python
1476+
left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
1477+
right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
1478+
```
1479+
1. If array shapes differ, left-pad the smaller shape with ones.
1480+
```python
1481+
left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
1482+
right = [[0.1 , 0.6 , 0.8]]) # Shape: (1, 3) <- !
1483+
```
1484+
2. If any dimensions differ in size, expand the ones that have size 1, by duplicating their elements.
1485+
```python
1486+
left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
1487+
right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
1488+
```
1489+
3. If neither non-matching dimension has size 1, rise an error.
1490+
1491+
### Example
1492+
**For each point returns index of its nearest point: `[0.1, 0.6, 0.8] => [1, 2, 1])`.**
1493+
```python
1494+
>>> points = np.array([0.1, 0.6, 0.8])
1495+
array([ 0.1, 0.6, 0.8])
1496+
>>> wrapped_points = points.reshape(3, 1)
1497+
array([[ 0.1],
1498+
[ 0.6],
1499+
[ 0.8]])
1500+
>>> distances = wrapped_points - points
1501+
array([[ 0. , -0.5, -0.7],
1502+
[ 0.5, 0. , -0.2],
1503+
[ 0.7, 0.2, 0. ]])
1504+
>>> distances = np.abs(distances)
1505+
array([[ 0. , 0.5, 0.7],
1506+
[ 0.5, 0. , 0.2],
1507+
[ 0.7, 0.2, 0. ]])
1508+
>>> i = np.arange(3)
1509+
array([0, 1, 2])
1510+
>>> distances[i, i] = np.inf
1511+
array([[ inf, 0.5, 0.7],
1512+
[ 0.5, inf, 0.2],
1513+
[ 0.7, 0.2, inf]])
1514+
>>> distances.argmin(1)
1515+
array([1, 2, 1])
1516+
```
1517+
1518+
14521519
Basic Script Template
14531520
---------------------
14541521
```python

0 commit comments

Comments
 (0)