immutable: int, float, tuple, string
mutable: list, dict, class, set, numpy.ndarray
>>> a = 1
>>> b = a
>>> b = 3
>>> a
1
int值不会改变
>>> a = {2,3}
>>> b = a
>>> b.add(4)
>>> a
{2, 3, 4}
set会改变
>>> import numpy as np
>>> a = np.array([[1,2,3,4],[5,6,7,8]])
>>> a
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
>>> b = a[1,:]
>>> b
array([5, 6, 7, 8])
>>> b[0] = 100
>>> a
array([[ 1, 2, 3, 4],
[100, 6, 7, 8]])
array会改变
[一首歌。。。]
The Onlyhttps://c.y.qq.com/base/fcgi-bin/u?__=xvQRGchttps://c.y.qq.com/base/fcgi-bin/u?__=xvQRGc
np.arange(n) = list(range(n))
>>> np.arange(4)
array([0, 1, 2, 3])
Array Math
matrix multiplication
print(v.dot(w))
print(np.dot(v, w))
np.dot() = @
np.sum()
print(np.sum(x)) # Compute sum of all elements; prints "10"
print(np.sum(x, axis=0)) # Compute sum of each column; prints "[4 6]"
print(np.sum(x, axis=1)) # Compute sum of each row; prints "[3 7]"
np.exp()
np.log()
Broadcasting
y = np.empty_like(x) # Create an empty matrix with the same shape as x
重复某一行
Numpy broadcasting allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:
import numpy as np
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v # Add v to each row of x using broadcasting
print(y)
Broadcasting two arrays together follows these rules:
- If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.
- The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.
- The arrays can be broadcast together if they are compatible in all dimensions.
- After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.
- In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension
列加还是行加 要小心
Matplotlib.pyplot
Matplotlib is a plotting library. In this section give a brief introduction to the matplotlib.pyplot
module, which provides a plotting system similar to that of MATLAB.
y_sin = np.sin(x)
y_cos = np.cos(x)
# Plot the points using matplotlib
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
subplot
# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
# Set up a subplot grid that has height 2 and width 1,
# and set the first such subplot as active.
plt.subplot(2, 1, 1)
# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')
# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')
# Show the figure.
plt.show()