Where¶
In [2]:
%pip install numpy
import numpy as np
Requirement already satisfied: numpy in /home/samrat/Documents/numpy-torch-tutorials/venv/lib/python3.8/site-packages (1.24.4) Note: you may need to restart the kernel to use updated packages.
In [5]:
generator = np.random.default_rng()
foo = generator.integers(6, size=2*10**6)
foo
Out[5]:
array([3, 5, 5, ..., 5, 0, 2])
In [8]:
bar = generator.integers(6,size=2*10**6)
bar
Out[8]:
array([3, 5, 0, ..., 0, 5, 5])
In [13]:
%%timeit
baz = np.zeros(foo.size)
for i in range(foo.size):
if bar[i] % 2 == 0:
baz[i] = foo[i] * 2
else:
baz[i] = foo[i] / 2
print(baz)
[ 1.5 2.5 10. ... 10. 0. 1. ] [ 1.5 2.5 10. ... 10. 0. 1. ] [ 1.5 2.5 10. ... 10. 0. 1. ] [ 1.5 2.5 10. ... 10. 0. 1. ] [ 1.5 2.5 10. ... 10. 0. 1. ] [ 1.5 2.5 10. ... 10. 0. 1. ] [ 1.5 2.5 10. ... 10. 0. 1. ] [ 1.5 2.5 10. ... 10. 0. 1. ] 764 ms ± 23.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [14]:
%%timeit
boz = np.where(bar %2 == 0, foo *2, foo/2)
33.1 ms ± 5.73 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [15]:
np.array_equal(baz, boz)
Out[15]:
True