PythonMastery
reference 6 min read · lesson 17 of 25 in Reference

NumPy Arrays Cheat Sheet

1 · The lesson

read

Python has no built-in array type. When people say "array" in Python, they usually mean a NumPy array: a grid of numbers, all of one type, that you can do maths on all at once, without writing a loop. If you want plain Python lists, see the list cheat sheet. For the full tutorials, see NumPy and NumPy for data science.

The standard library also has an array module, but it is rarely used. NumPy is what most code uses. On your own computer, install it with pip install numpy. Every example here starts with import numpy as np.

1. Create an array

python
import numpy as np

print(np.array([1, 2, 3]))        # [1 2 3]
print(np.zeros(3))                # [0. 0. 0.]
print(np.arange(0, 10, 3))        # [0 3 6 9]
print(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]
print(np.ones((2, 2), dtype=int))
python
[1 2 3]
[0. 0. 0.]
[0 3 6 9]
[0.   0.25 0.5  0.75 1.  ]
[[1 1]
 [1 1]]

np.zeros() gives floats by default, so 0. means 0.0. np.arange() works like range(): the stop value is not included. np.linspace(0, 1, 5) gives 5 evenly spaced values and does include the end. For a 2-D array, the shape (rows, columns) goes in brackets.

2. Shape and type

The shape tells you how many items there are in each direction. The dtype is the one type that every item has.

python
m = np.array([[1, 2, 3], [4, 5, 6]])

print(m.shape)     # (2, 3)
print(m.ndim)      # 2
print(m.size)      # 6
print(np.array([0.5, 2]).dtype)   # float64
print(m.astype(float)[0])         # [1. 2. 3.]
+ setup added so this can run · re-runs 1 earlier block on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

m.shape is (2, 3): 2 rows and 3 columns. ndim is the number of dimensions. astype() makes a copy with a new type.

3. Index and slice

For a 2-D array, put the row first and the column second, separated by a comma.

python
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m[0, 1])     # 2
print(m[1])        # [4 5 6]
print(m[:, 0])     # [1 4]
print(m[:, 1:])
+ setup added so this can run · re-runs 2 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier
python
2
[4 5 6]
[1 4]
[[2 3]
 [5 6]]

m[:, 0] means "all rows, column 0", so you get the first column.

A test such as v > 15 gives one True or False for each item. This is called a boolean mask. Put the mask inside the square brackets to keep only the items where the mask is True.

python
v = np.array([10, 20, 30, 40])
print(v > 15)          # [False  True  True  True]
print(v[v > 15])       # [20 30 40]
print(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2
v[v > 25] = 0          # set every item above 25 to 0
print(v)               # [10 20  0  0]
+ setup added so this can run · re-runs 3 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

4. Maths on every item

Maths on an array happens item by item. You do not need a loop.

python
prices = np.array([2.5, 4.0, 10.0])
qty = np.array([2, 1, 3])

print(prices * qty)              # [ 5.  4. 30.]
print(prices + 1)                # [ 3.5  5.  11. ]
print(float((prices * qty).sum()))   # 39.0

celsius = np.array([20, 25, 30])
print(celsius * 9 / 5 + 32)      # [68. 77. 86.]
print(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]
+ setup added so this can run · re-runs 4 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

.sum() gives a NumPy number. float() turns it into a plain Python number.

5. Broadcasting

When two arrays have different shapes, NumPy repeats the smaller one so that it matches the bigger one. This is called broadcasting. It works when the sizes line up from the right: a single number goes with every item, and a row of 3 goes with every row of a 2 x 3 array.

python
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m * 10)
print(m + np.array([100, 200, 300]))
+ setup added so this can run · re-runs 5 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
    'prices = np.array([2.5, 4.0, 10.0])\nqty = np.array([2, 1, 3])\n\nprint(prices * qty)              # [ 5.  4. 30.]\nprint(prices + 1)                # [ 3.5  5.  11. ]\nprint(float((prices * qty).sum()))   # 39.0\n\ncelsius = np.array([20, 25, 30])\nprint(celsius * 9 / 5 + 32)      # [68. 77. 86.]\nprint(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier
python
[[10 20 30]
 [40 50 60]]
[[101 202 303]
 [104 205 306]]

If the sizes do not line up, you get an error:

python
try:
    m + np.array([1, 2])
except ValueError:
    print("ValueError: shapes (2, 3) and (2,) don't fit")
+ setup added so this can run · re-runs 6 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

m = _AutoMock('m')
np = _AutoMock('np')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
    'prices = np.array([2.5, 4.0, 10.0])\nqty = np.array([2, 1, 3])\n\nprint(prices * qty)              # [ 5.  4. 30.]\nprint(prices + 1)                # [ 3.5  5.  11. ]\nprint(float((prices * qty).sum()))   # 39.0\n\ncelsius = np.array([20, 25, 30])\nprint(celsius * 9 / 5 + 32)      # [68. 77. 86.]\nprint(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m * 10)\nprint(m + np.array([100, 200, 300]))',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

6. Change the shape

python
v = np.arange(6)
print(v.reshape(2, 3))
print(v.reshape(3, -1).shape)    # (3, 2)

m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.T)
print(m.flatten())               # [1 2 3 4 5 6]
+ setup added so this can run · re-runs 7 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')
m = _AutoMock('m')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
    'prices = np.array([2.5, 4.0, 10.0])\nqty = np.array([2, 1, 3])\n\nprint(prices * qty)              # [ 5.  4. 30.]\nprint(prices + 1)                # [ 3.5  5.  11. ]\nprint(float((prices * qty).sum()))   # 39.0\n\ncelsius = np.array([20, 25, 30])\nprint(celsius * 9 / 5 + 32)      # [68. 77. 86.]\nprint(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m * 10)\nprint(m + np.array([100, 200, 300]))',
    'try:\n    m + np.array([1, 2])\nexcept ValueError:\n    print("ValueError: shapes (2, 3) and (2,) don\'t fit")',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier
python
[[0 1 2]
 [3 4 5]]
(3, 2)
[[1 4]
 [2 5]
 [3 6]]
[1 2 3 4 5 6]

reshape() keeps the same items and puts them in a new shape. -1 means "work out this size for me". m.T is the transpose: rows become columns. flatten() gives a 1-D copy.

7. Totals and the axis argument

An axis is one direction of the grid. axis=0 goes down the rows, so you get one answer per column. axis=1 goes across each row, so you get one answer per row.

python
scores = np.array([[70, 80, 90],    # Ada
                   [60, 75, 90]])   # Grace

print(int(scores.sum()))       # 465
print(scores.sum(axis=0))      # [130 155 180]
print(scores.mean(axis=1))     # [80. 75.]
print(scores.max(axis=0))      # [70 80 90]
+ setup added so this can run · re-runs 8 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')
m = _AutoMock('m')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
    'prices = np.array([2.5, 4.0, 10.0])\nqty = np.array([2, 1, 3])\n\nprint(prices * qty)              # [ 5.  4. 30.]\nprint(prices + 1)                # [ 3.5  5.  11. ]\nprint(float((prices * qty).sum()))   # 39.0\n\ncelsius = np.array([20, 25, 30])\nprint(celsius * 9 / 5 + 32)      # [68. 77. 86.]\nprint(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m * 10)\nprint(m + np.array([100, 200, 300]))',
    'try:\n    m + np.array([1, 2])\nexcept ValueError:\n    print("ValueError: shapes (2, 3) and (2,) don\'t fit")',
    'v = np.arange(6)\nprint(v.reshape(2, 3))\nprint(v.reshape(3, -1).shape)    # (3, 2)\n\nm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m.T)\nprint(m.flatten())               # [1 2 3 4 5 6]',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

Here each column is a test, so axis=0 gives a total per test. Each row is a student, so axis=1 gives an average per student. min(), std() and cumsum() take axis in the same way.

8. Useful functions

python
t = np.array([18, 25, 31, 25, 12])

print(np.where(t > 24, t, 0))    # [ 0 25 31 25  0]
print(np.unique(t))              # [12 18 25 31]
print(np.sort(t))                # [12 18 25 25 31]
print(int(np.argmax(t)))         # 2
print(np.round(np.array([3.14159, 2.71828]), 2))   # [3.14 2.72]
+ setup added so this can run · re-runs 9 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')
m = _AutoMock('m')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
    'prices = np.array([2.5, 4.0, 10.0])\nqty = np.array([2, 1, 3])\n\nprint(prices * qty)              # [ 5.  4. 30.]\nprint(prices + 1)                # [ 3.5  5.  11. ]\nprint(float((prices * qty).sum()))   # 39.0\n\ncelsius = np.array([20, 25, 30])\nprint(celsius * 9 / 5 + 32)      # [68. 77. 86.]\nprint(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m * 10)\nprint(m + np.array([100, 200, 300]))',
    'try:\n    m + np.array([1, 2])\nexcept ValueError:\n    print("ValueError: shapes (2, 3) and (2,) don\'t fit")',
    'v = np.arange(6)\nprint(v.reshape(2, 3))\nprint(v.reshape(3, -1).shape)    # (3, 2)\n\nm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m.T)\nprint(m.flatten())               # [1 2 3 4 5 6]',
    'scores = np.array([[70, 80, 90],    # Ada\n                   [60, 75, 90]])   # Grace\n\nprint(int(scores.sum()))       # 465\nprint(scores.sum(axis=0))      # [130 155 180]\nprint(scores.mean(axis=1))     # [80. 75.]\nprint(scores.max(axis=0))      # [70 80 90]',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

np.where(test, a, b) takes a where the test is True and b where it is False. np.sort() returns a sorted copy and does not change t. np.argmax() gives the position of the biggest value, not the value.

9. Random numbers

Make a generator with a seed (here 42). The same seed gives the same numbers every time you run the code, so other people can repeat your results.

python
rng = np.random.default_rng(42)
names = ["Ada", "Grace", "Linus", "Hedy"]

print(rng.integers(1, 7, size=5))         # [1 5 4 3 3]
print(rng.random(3).round(2))             # [0.7  0.09 0.98]
print(rng.choice(names, size=2, replace=False).tolist())   # ['Linus', 'Hedy']
print(rng.normal(170, 10, size=3).round(1))   # [166.8 169.8 161.5]
+ setup added so this can run · re-runs 10 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')
m = _AutoMock('m')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
    'prices = np.array([2.5, 4.0, 10.0])\nqty = np.array([2, 1, 3])\n\nprint(prices * qty)              # [ 5.  4. 30.]\nprint(prices + 1)                # [ 3.5  5.  11. ]\nprint(float((prices * qty).sum()))   # 39.0\n\ncelsius = np.array([20, 25, 30])\nprint(celsius * 9 / 5 + 32)      # [68. 77. 86.]\nprint(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m * 10)\nprint(m + np.array([100, 200, 300]))',
    'try:\n    m + np.array([1, 2])\nexcept ValueError:\n    print("ValueError: shapes (2, 3) and (2,) don\'t fit")',
    'v = np.arange(6)\nprint(v.reshape(2, 3))\nprint(v.reshape(3, -1).shape)    # (3, 2)\n\nm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m.T)\nprint(m.flatten())               # [1 2 3 4 5 6]',
    'scores = np.array([[70, 80, 90],    # Ada\n                   [60, 75, 90]])   # Grace\n\nprint(int(scores.sum()))       # 465\nprint(scores.sum(axis=0))      # [130 155 180]\nprint(scores.mean(axis=1))     # [80. 75.]\nprint(scores.max(axis=0))      # [70 80 90]',
    't = np.array([18, 25, 31, 25, 12])\n\nprint(np.where(t > 24, t, 0))    # [ 0 25 31 25  0]\nprint(np.unique(t))              # [12 18 25 31]\nprint(np.sort(t))                # [12 18 25 25 31]\nprint(int(np.argmax(t)))         # 2\nprint(np.round(np.array([3.14159, 2.71828]), 2))   # [3.14 2.72]',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

integers(1, 7) gives dice rolls: 7 is not included. random() gives floats from 0 up to 1. normal(170, 10) gives values around an average of 170 with a typical spread of 10.

Common mistakes

A slice is a view, not a copy. A slice shares its data with the original array, so changing the slice changes the original too.

python
v = np.array([1, 2, 3])
s = v[:2]
s[0] = 99
print(v)              # [99  2  3]

v = np.array([1, 2, 3])
s = v[:2].copy()      # the fix: an independent copy
s[0] = 99
print(v)              # [1 2 3]
+ setup added so this can run · re-runs 11 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')
m = _AutoMock('m')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
    'prices = np.array([2.5, 4.0, 10.0])\nqty = np.array([2, 1, 3])\n\nprint(prices * qty)              # [ 5.  4. 30.]\nprint(prices + 1)                # [ 3.5  5.  11. ]\nprint(float((prices * qty).sum()))   # 39.0\n\ncelsius = np.array([20, 25, 30])\nprint(celsius * 9 / 5 + 32)      # [68. 77. 86.]\nprint(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m * 10)\nprint(m + np.array([100, 200, 300]))',
    'try:\n    m + np.array([1, 2])\nexcept ValueError:\n    print("ValueError: shapes (2, 3) and (2,) don\'t fit")',
    'v = np.arange(6)\nprint(v.reshape(2, 3))\nprint(v.reshape(3, -1).shape)    # (3, 2)\n\nm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m.T)\nprint(m.flatten())               # [1 2 3 4 5 6]',
    'scores = np.array([[70, 80, 90],    # Ada\n                   [60, 75, 90]])   # Grace\n\nprint(int(scores.sum()))       # 465\nprint(scores.sum(axis=0))      # [130 155 180]\nprint(scores.mean(axis=1))     # [80. 75.]\nprint(scores.max(axis=0))      # [70 80 90]',
    't = np.array([18, 25, 31, 25, 12])\n\nprint(np.where(t > 24, t, 0))    # [ 0 25 31 25  0]\nprint(np.unique(t))              # [12 18 25 31]\nprint(np.sort(t))                # [12 18 25 25 31]\nprint(int(np.argmax(t)))         # 2\nprint(np.round(np.array([3.14159, 2.71828]), 2))   # [3.14 2.72]',
    'rng = np.random.default_rng(42)\nnames = ["Ada", "Grace", "Linus", "Hedy"]\n\nprint(rng.integers(1, 7, size=5))         # [1 5 4 3 3]\nprint(rng.random(3).round(2))             # [0.7  0.09 0.98]\nprint(rng.choice(names, size=2, replace=False).tolist())   # [\'Linus\', \'Hedy\']\nprint(rng.normal(170, 10, size=3).round(1))   # [166.8 169.8 161.5]',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

== compares item by item. v == 1 is an array, so if v == 1: raises a ValueError ("truth value of an array is ambiguous"). Choose the check you mean: .any() (at least one item is equal), .all() (every item is equal) or np.array_equal() (the two whole arrays are equal).

python
v = np.array([1, 2, 3])
print(v == 1)                                 # [ True False False]
print((v == 1).any())                         # True
print(np.array_equal(v, np.array([1, 2, 3]))) # True
+ setup added so this can run · re-runs 12 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')
m = _AutoMock('m')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
    'prices = np.array([2.5, 4.0, 10.0])\nqty = np.array([2, 1, 3])\n\nprint(prices * qty)              # [ 5.  4. 30.]\nprint(prices + 1)                # [ 3.5  5.  11. ]\nprint(float((prices * qty).sum()))   # 39.0\n\ncelsius = np.array([20, 25, 30])\nprint(celsius * 9 / 5 + 32)      # [68. 77. 86.]\nprint(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m * 10)\nprint(m + np.array([100, 200, 300]))',
    'try:\n    m + np.array([1, 2])\nexcept ValueError:\n    print("ValueError: shapes (2, 3) and (2,) don\'t fit")',
    'v = np.arange(6)\nprint(v.reshape(2, 3))\nprint(v.reshape(3, -1).shape)    # (3, 2)\n\nm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m.T)\nprint(m.flatten())               # [1 2 3 4 5 6]',
    'scores = np.array([[70, 80, 90],    # Ada\n                   [60, 75, 90]])   # Grace\n\nprint(int(scores.sum()))       # 465\nprint(scores.sum(axis=0))      # [130 155 180]\nprint(scores.mean(axis=1))     # [80. 75.]\nprint(scores.max(axis=0))      # [70 80 90]',
    't = np.array([18, 25, 31, 25, 12])\n\nprint(np.where(t > 24, t, 0))    # [ 0 25 31 25  0]\nprint(np.unique(t))              # [12 18 25 31]\nprint(np.sort(t))                # [12 18 25 25 31]\nprint(int(np.argmax(t)))         # 2\nprint(np.round(np.array([3.14159, 2.71828]), 2))   # [3.14 2.72]',
    'rng = np.random.default_rng(42)\nnames = ["Ada", "Grace", "Linus", "Hedy"]\n\nprint(rng.integers(1, 7, size=5))         # [1 5 4 3 3]\nprint(rng.random(3).round(2))             # [0.7  0.09 0.98]\nprint(rng.choice(names, size=2, replace=False).tolist())   # [\'Linus\', \'Hedy\']\nprint(rng.normal(170, 10, size=3).round(1))   # [166.8 169.8 161.5]',
    'v = np.array([1, 2, 3])\ns = v[:2]\ns[0] = 99\nprint(v)              # [99  2  3]\n\nv = np.array([1, 2, 3])\ns = v[:2].copy()      # the fix: an independent copy\ns[0] = 99\nprint(v)              # [1 2 3]',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

and and or don't work on arrays. v > 1 and v < 3 raises a ValueError. Use & (and) or | (or), with brackets around each test.

python
v = np.array([1, 2, 3])
print(v[(v > 1) & (v < 3)])   # [2]
+ setup added so this can run · re-runs 13 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')
m = _AutoMock('m')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
    'prices = np.array([2.5, 4.0, 10.0])\nqty = np.array([2, 1, 3])\n\nprint(prices * qty)              # [ 5.  4. 30.]\nprint(prices + 1)                # [ 3.5  5.  11. ]\nprint(float((prices * qty).sum()))   # 39.0\n\ncelsius = np.array([20, 25, 30])\nprint(celsius * 9 / 5 + 32)      # [68. 77. 86.]\nprint(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m * 10)\nprint(m + np.array([100, 200, 300]))',
    'try:\n    m + np.array([1, 2])\nexcept ValueError:\n    print("ValueError: shapes (2, 3) and (2,) don\'t fit")',
    'v = np.arange(6)\nprint(v.reshape(2, 3))\nprint(v.reshape(3, -1).shape)    # (3, 2)\n\nm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m.T)\nprint(m.flatten())               # [1 2 3 4 5 6]',
    'scores = np.array([[70, 80, 90],    # Ada\n                   [60, 75, 90]])   # Grace\n\nprint(int(scores.sum()))       # 465\nprint(scores.sum(axis=0))      # [130 155 180]\nprint(scores.mean(axis=1))     # [80. 75.]\nprint(scores.max(axis=0))      # [70 80 90]',
    't = np.array([18, 25, 31, 25, 12])\n\nprint(np.where(t > 24, t, 0))    # [ 0 25 31 25  0]\nprint(np.unique(t))              # [12 18 25 31]\nprint(np.sort(t))                # [12 18 25 25 31]\nprint(int(np.argmax(t)))         # 2\nprint(np.round(np.array([3.14159, 2.71828]), 2))   # [3.14 2.72]',
    'rng = np.random.default_rng(42)\nnames = ["Ada", "Grace", "Linus", "Hedy"]\n\nprint(rng.integers(1, 7, size=5))         # [1 5 4 3 3]\nprint(rng.random(3).round(2))             # [0.7  0.09 0.98]\nprint(rng.choice(names, size=2, replace=False).tolist())   # [\'Linus\', \'Hedy\']\nprint(rng.normal(170, 10, size=3).round(1))   # [166.8 169.8 161.5]',
    'v = np.array([1, 2, 3])\ns = v[:2]\ns[0] = 99\nprint(v)              # [99  2  3]\n\nv = np.array([1, 2, 3])\ns = v[:2].copy()      # the fix: an independent copy\ns[0] = 99\nprint(v)              # [1 2 3]',
    'v = np.array([1, 2, 3])\nprint(v == 1)                                 # [ True False False]\nprint((v == 1).any())                         # True\nprint(np.array_equal(v, np.array([1, 2, 3]))) # True',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

An int array drops decimals. Putting a float into an int array cuts off the decimal part without any warning. Make the array a float array if you need decimals.

python
w = np.array([1, 2])
w[0] = 9.7
print(w)                      # [9 2]

w = np.array([1, 2], dtype=float)
w[0] = 9.7
print(w)                      # [9.7 2. ]
+ setup added so this can run · re-runs 14 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')
m = _AutoMock('m')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
    'prices = np.array([2.5, 4.0, 10.0])\nqty = np.array([2, 1, 3])\n\nprint(prices * qty)              # [ 5.  4. 30.]\nprint(prices + 1)                # [ 3.5  5.  11. ]\nprint(float((prices * qty).sum()))   # 39.0\n\ncelsius = np.array([20, 25, 30])\nprint(celsius * 9 / 5 + 32)      # [68. 77. 86.]\nprint(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m * 10)\nprint(m + np.array([100, 200, 300]))',
    'try:\n    m + np.array([1, 2])\nexcept ValueError:\n    print("ValueError: shapes (2, 3) and (2,) don\'t fit")',
    'v = np.arange(6)\nprint(v.reshape(2, 3))\nprint(v.reshape(3, -1).shape)    # (3, 2)\n\nm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m.T)\nprint(m.flatten())               # [1 2 3 4 5 6]',
    'scores = np.array([[70, 80, 90],    # Ada\n                   [60, 75, 90]])   # Grace\n\nprint(int(scores.sum()))       # 465\nprint(scores.sum(axis=0))      # [130 155 180]\nprint(scores.mean(axis=1))     # [80. 75.]\nprint(scores.max(axis=0))      # [70 80 90]',
    't = np.array([18, 25, 31, 25, 12])\n\nprint(np.where(t > 24, t, 0))    # [ 0 25 31 25  0]\nprint(np.unique(t))              # [12 18 25 31]\nprint(np.sort(t))                # [12 18 25 25 31]\nprint(int(np.argmax(t)))         # 2\nprint(np.round(np.array([3.14159, 2.71828]), 2))   # [3.14 2.72]',
    'rng = np.random.default_rng(42)\nnames = ["Ada", "Grace", "Linus", "Hedy"]\n\nprint(rng.integers(1, 7, size=5))         # [1 5 4 3 3]\nprint(rng.random(3).round(2))             # [0.7  0.09 0.98]\nprint(rng.choice(names, size=2, replace=False).tolist())   # [\'Linus\', \'Hedy\']\nprint(rng.normal(170, 10, size=3).round(1))   # [166.8 169.8 161.5]',
    'v = np.array([1, 2, 3])\ns = v[:2]\ns[0] = 99\nprint(v)              # [99  2  3]\n\nv = np.array([1, 2, 3])\ns = v[:2].copy()      # the fix: an independent copy\ns[0] = 99\nprint(v)              # [1 2 3]',
    'v = np.array([1, 2, 3])\nprint(v == 1)                                 # [ True False False]\nprint((v == 1).any())                         # True\nprint(np.array_equal(v, np.array([1, 2, 3]))) # True',
    'v = np.array([1, 2, 3])\nprint(v[(v > 1) & (v < 3)])   # [2]',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

A list times 2 is not an array times 2. A list repeats itself. An array multiplies every item.

python
print([1, 2] * 2)             # [1, 2, 1, 2]
print(np.array([1, 2]) * 2)   # [2 4]
+ setup added so this can run · re-runs 15 earlier blocks on this page first
# Lightweight mock for objects whose attributes/methods aren't critical
class _AutoMock:
    def __init__(self, name='mock'): self._name = name
    def __getattr__(self, k): return _AutoMock(self._name + '.' + k)
    def __call__(self, *a, **kw):
        print('-> ' + self._name + '() called')
        return _AutoMock(self._name + '()')
    def __repr__(self): return '<mock ' + self._name + '>'
    def __str__(self): return '<mock ' + self._name + '>'
    def __bool__(self): return True
    def __iter__(self): return iter([])
    def __len__(self): return 0
    def __getitem__(self, k): return _AutoMock(self._name + '[...]')
    def __setitem__(self, k, v): pass
    def __enter__(self): return self
    def __exit__(self, *a): return False
    async def __aenter__(self): return self
    async def __aexit__(self, *a): return False
    def __add__(self, o): return self
    def __radd__(self, o): return self
    def __sub__(self, o): return self
    def __mul__(self, o): return self
    def __rmul__(self, o): return self
    def __truediv__(self, o): return self
    def __eq__(self, o): return isinstance(o, _AutoMock)
    def __hash__(self): return hash(self._name)
    def __lt__(self, o): return True
    def __le__(self, o): return True
    def __gt__(self, o): return False
    def __ge__(self, o): return False
    def __mro_entries__(self, bases): return (object,)

np = _AutoMock('np')
m = _AutoMock('m')

# Earlier blocks on this page that this one builds on, re-run quietly first.
try:
    import numpy as np
except Exception:
    pass
_pm_earlier = [
    'import numpy as np\n\nprint(np.array([1, 2, 3]))        # [1 2 3]\nprint(np.zeros(3))                # [0. 0. 0.]\nprint(np.arange(0, 10, 3))        # [0 3 6 9]\nprint(np.linspace(0, 1, 5))       # [0.   0.25 0.5  0.75 1.  ]\nprint(np.ones((2, 2), dtype=int))',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\n\nprint(m.shape)     # (2, 3)\nprint(m.ndim)      # 2\nprint(m.size)      # 6\nprint(np.array([0.5, 2]).dtype)   # float64\nprint(m.astype(float)[0])         # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m[0, 1])     # 2\nprint(m[1])        # [4 5 6]\nprint(m[:, 0])     # [1 4]\nprint(m[:, 1:])',
    'v = np.array([10, 20, 30, 40])\nprint(v > 15)          # [False  True  True  True]\nprint(v[v > 15])       # [20 30 40]\nprint(v[[0, 2]])       # [10 30]: a list of positions picks items 0 and 2\nv[v > 25] = 0          # set every item above 25 to 0\nprint(v)               # [10 20  0  0]',
    'prices = np.array([2.5, 4.0, 10.0])\nqty = np.array([2, 1, 3])\n\nprint(prices * qty)              # [ 5.  4. 30.]\nprint(prices + 1)                # [ 3.5  5.  11. ]\nprint(float((prices * qty).sum()))   # 39.0\n\ncelsius = np.array([20, 25, 30])\nprint(celsius * 9 / 5 + 32)      # [68. 77. 86.]\nprint(np.sqrt(np.array([1, 4, 9])))  # [1. 2. 3.]',
    'm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m * 10)\nprint(m + np.array([100, 200, 300]))',
    'try:\n    m + np.array([1, 2])\nexcept ValueError:\n    print("ValueError: shapes (2, 3) and (2,) don\'t fit")',
    'v = np.arange(6)\nprint(v.reshape(2, 3))\nprint(v.reshape(3, -1).shape)    # (3, 2)\n\nm = np.array([[1, 2, 3], [4, 5, 6]])\nprint(m.T)\nprint(m.flatten())               # [1 2 3 4 5 6]',
    'scores = np.array([[70, 80, 90],    # Ada\n                   [60, 75, 90]])   # Grace\n\nprint(int(scores.sum()))       # 465\nprint(scores.sum(axis=0))      # [130 155 180]\nprint(scores.mean(axis=1))     # [80. 75.]\nprint(scores.max(axis=0))      # [70 80 90]',
    't = np.array([18, 25, 31, 25, 12])\n\nprint(np.where(t > 24, t, 0))    # [ 0 25 31 25  0]\nprint(np.unique(t))              # [12 18 25 31]\nprint(np.sort(t))                # [12 18 25 25 31]\nprint(int(np.argmax(t)))         # 2\nprint(np.round(np.array([3.14159, 2.71828]), 2))   # [3.14 2.72]',
    'rng = np.random.default_rng(42)\nnames = ["Ada", "Grace", "Linus", "Hedy"]\n\nprint(rng.integers(1, 7, size=5))         # [1 5 4 3 3]\nprint(rng.random(3).round(2))             # [0.7  0.09 0.98]\nprint(rng.choice(names, size=2, replace=False).tolist())   # [\'Linus\', \'Hedy\']\nprint(rng.normal(170, 10, size=3).round(1))   # [166.8 169.8 161.5]',
    'v = np.array([1, 2, 3])\ns = v[:2]\ns[0] = 99\nprint(v)              # [99  2  3]\n\nv = np.array([1, 2, 3])\ns = v[:2].copy()      # the fix: an independent copy\ns[0] = 99\nprint(v)              # [1 2 3]',
    'v = np.array([1, 2, 3])\nprint(v == 1)                                 # [ True False False]\nprint((v == 1).any())                         # True\nprint(np.array_equal(v, np.array([1, 2, 3]))) # True',
    'v = np.array([1, 2, 3])\nprint(v[(v > 1) & (v < 3)])   # [2]',
    'w = np.array([1, 2])\nw[0] = 9.7\nprint(w)                      # [9 2]\n\nw = np.array([1, 2], dtype=float)\nw[0] = 9.7\nprint(w)                      # [9.7 2. ]',
]
def _pm_run_earlier(_srcs, _g):
    import sys as _s, io as _io, warnings as _w
    for _src in _srcs:
        _o, _e = _s.stdout, _s.stderr
        _s.stdout = _s.stderr = _io.StringIO()
        try:
            with _w.catch_warnings():
                _w.simplefilter('ignore')
                exec(compile(_src, '<earlier block>', 'exec'), _g)
        except (Exception, SystemExit):
            pass
        finally:
            _s.stdout, _s.stderr = _o, _e
    if 'matplotlib.pyplot' in _s.modules:
        _s.modules['matplotlib.pyplot'].close('all')   # their plots belong to their own blocks
_pm_run_earlier(_pm_earlier, globals())
del _pm_earlier, _pm_run_earlier

Found this useful? Share it with a friend who’s learning Python.