#具体做法就是传入一个list或tuple作为参数 a = np.array([1,2,3,4]) #一种典型的错误情况:a = np.array(1,2,3,4)
#如果传入由多个list或tuple构成的list或tuple作为参数,遵守这个规律: #array transforms sequences of sequences into two-dimensional arrays, #sequences of sequences of sequences into three-dimensional arrays, #and so on. b = np.array([(1.5,2,3), (4,5,6)])
#自定义元素类型 c = np.array( [ [1,2], [3,4] ], dtype=complex )
#一维数组:不一样 a = np.array([4.,2.]) b = np.array([3.,8.]) print('np.column_stack((a,b))是{}'.format(np.column_stack((a,b)))) print('np.hstack((a,b))是{}'.format(np.hstack((a,b))))
In general, for arrays with more than two dimensions, hstack stacks along their second axes, vstack stacks along their first axes, and concatenate allows for an optional arguments giving the number of the axis along which the concatenation should happen.
#一个图片的示例 palette = np.array([[0, 0, 0], # black [255, 0, 0], # red [0, 255, 0], # green [0, 0, 255], # blue [255, 255, 255]]) # white image = np.array([[0, 1, 2, 0], # each value corresponds to a color in the palette [0, 3, 4, 0]]) palette[image] # the (2, 4, 3) color image
#用多维索引对多维数组进行索引:对每一维度切片的索引数组必须有相同的shape a = np.arange(12).reshape(3,4) print('a是{}\n'.format(a)) i = np.array([[0, 1], # indices for the first dim of a [1, 2]]) j = np.array([[2, 1], # indices for the second dim [3, 3]])
print('a[i, j]是{}\n'.format(a[i, j])) # i and j must have equal shape print('a[i, 2]是{}\n'.format(a[i, 2])) print('a[:, j]是{}'.format(a[:, j])) # i.e., a[ : , j] #最后这个应该就是(2×2)矩阵,每个元素位置上放一个a[:,n]的向量。 #为什么是这个方向我有点没看懂,但是我能想象它的立体排布
#用列表索引赋值时,如果列表索引有重复,只会留下最后的赋值 #因为会运行多次赋值工作 a = np.arange(5) a[[0,0,2]]=[1,2,3] print(a)
#但是如果用+=: a = np.arange(5) a[[0,0,2]]+=1 print(a) #对这种现象的解释是: #Even though 0 occurs twice in the list of indices, #the 0th element is only incremented once. #This is because Python requires “a+=1” to be equivalent to “a = a + 1”. #我没看懂,但是反正是有这种现象
1 2 3 4 5 6
Output: >>
[01234] [00200] [21334] [11334]
5.2 布尔列表索引
情况1:索引数组和原数组拥有同样的shape
1 2 3 4 5 6 7
a = np.arange(12).reshape(3,4) print(a) b = a > 4 print(b) print(a[b]) a[b] = 0 print(a) #可以直接用以赋值
#画曼德布洛特集合 #(函数没看懂,但是反正就是布尔索引和被切片数组shape相同这种情况) import numpy as np import matplotlib.pyplot as plt defmandelbrot( h,w, maxit=20): """Returns an image of the Mandelbrot fractal of size (h,w).""" y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ] c = x+y*1j z = c divtime = maxit + np.zeros(z.shape, dtype=int)
for i inrange(maxit): z = z**2 + c diverge = z*np.conj(z) > 2**2# who is diverging div_now = diverge & (divtime==maxit) # who is diverging now divtime[div_now] = i # note when z[diverge] = 2# avoid diverging too much
return divtime
plt.imshow(mandelbrot(400,400))
1 2 3
Output: >>
<matplotlib.image.AxesImage at 0x2cf82a71088>
情况2:跟整数数组索引类似,对被切片数组每个维度用一维索引数组切片
索引数组必须要跟被切片数组对应维度等长
1 2 3 4 5 6 7 8 9 10 11 12
a = np.arange(12).reshape(3,4) print(a) print() b1 = np.array([False,True,True]) # first dim selection b2 = np.array([True,False,True,False]) # second dim selection print(a[b1]) print() print(a[b1,:]) print() print(a[:,b2]) print() print(a[b1,b2]) #……?这个结果为什么是这样
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Output: >>
[[ 0123] [ 4567] [ 891011]]
[[ 4567] [ 891011]]
[[ 4567] [ 891011]]
[[ 02] [ 46] [ 810]]
[ 410]
5.3 ix_():可以计算多个数组逐元素运算的情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#举例来说,可以对abc三个向量每个三元组计算a+b*c a = np.array([2,3,4,5]) b = np.array([8,5,4]) c = np.array([5,4,6,8,3]) ax,bx,cx = np.ix_(a,b,c) print(ax) print(bx) print(cx) print(ax.shape) print(bx.shape) print(cx.shape)
import numpy as np rg = np.random.default_rng(1) import matplotlib.pyplot as plt # Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2 mu, sigma = 2, 0.5 v = rg.normal(mu,sigma,10000) # Plot a normalized histogram with 50 bins plt.hist(v, bins=50, density=1) # matplotlib version (plot)直方图 # Compute the histogram with numpy and then plot it (n, bins) = np.histogram(v, bins=50, density=True) # NumPy version (no plot) plt.plot(.5*(bins[1:]+bins[:-1]), n) #折线图(这个计算平均值的方法好绝)