NumPy Introduction 3
broadcast
1 | import numpy as np |
1 | M = np.ones((3, 3)) |
1 | a = np.arange(3) |
rule of broadcast
1 | M = np.ones((2, 3)) |
we can know that:
M.shape=(2,3) ; a.shape=(3,)
to add this two,first add one more dimension to a: a.shape=(1,3)
then expand a: a.shape=(2,3)
e.g.
1 | a = np.arange(3).reshape((3, 1)) |
sometimes it may not success:
1 | M = np.ones((3, 2)) |
after broadcast
M.shape -> (3, 2)
a.shape -> (3, 3)
if you want to add number on the right of the shape,you can reshape the array:
1 | M + a[:, np.newaxis] #a's shape now is(3,1) |
this rules can be used with any common function:
1 | np.logaddexp(M, a[:, np.newaxis]) |
it’s more accurate than log(exp(a) + exp(b))
dealing with numbers
1 | X = np.random.random((10, 3)) |
check: whether they’re close to 0
1 | X_centered = X - Xmean |
plot the picture:
1 | x=np.linspace(0,5,50) |
mask
e.g. record the raining days
1 | import numpy as np |
compare the value
1 | x = np.array([1, 2, 3, 4, 5]) |
Boolean
1 | print(x) |
Boolean symbols can also be used:
1 | np.sum((inches > 0.5) & (inches < 1)) #count the date of raining within the standard |
& | np.bitwise_and |
---|---|
| | np.bitwise_or |
^ | np.bitwise_xor |
~ | np.bitwise_not |
1 | print("Number days without rain: ", np.sum(inches == 0)) |
use Boolean as mask
1 | x |
easier way to get index
1 | import numpy as np |
change the value:
1 | x = np.arange(10) |
another way:
1 | x = np.zeros(10) |
sort the array
know more about sort: https://arya-1017.github.io/2020/07/12/《算法图解》读书笔记1/
and https://arya-1017.github.io/2020/07/13/《算法图解》读书笔记2/
1 | import numpy as np |
easier way:
1 | x = np.array([2, 1, 4, 3, 5]) |
multi-dimension array:
1 | rand = np.random.RandomState(42) |
sort partially:
1 | x = np.array([7, 2, 3, 1, 6, 5, 4]) |